Skip to content

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

fix(auth): refuse to turn off the last working sign-in method on the server (ENG-1053) (#17008)

lina-alomarif1f49f65ffbc
diff --git a/packages/server/api/src/app/authentication/authentication-utils.ts b/packages/server/api/src/app/authentication/authentication-utils.ts
index 1c37c71dabd..cbcb77e3081 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, PlatformWithoutSensitiveData, PrincipalType, Project, ProjectType, SsoDomainVerificationStatus, TelemetryEventName, User, UserIdentity, UserIdentityProvider, UserStatus } from '@activepieces/shared'
+import { ApEdition, ApEnvironment, AuthenticationResponse, EndpointScope, pickTelemetryPii, Platform, 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'
@@ -268,13 +268,14 @@ export const authenticationUtils = (log: FastifyBaseLogger) => ({
return project.ownerId
},
getSignInMethods({ platform }: GetSignInMethodsParams): SignInMethods {
- if (system.getEdition() === ApEdition.COMMUNITY) {
+ const edition = system.getEdition()
+ if (edition === ApEdition.COMMUNITY) {
return { email: true, google: false, sso: false }
}
return {
email: platform.emailAuthEnabled,
google: isGoogleConfigured() && platform.googleAuthEnabled,
- sso: !isNil(platform.federatedAuthProviders?.saml),
+ sso: !isNil(platform.federatedAuthProviders?.saml) && (edition !== ApEdition.CLOUD || platform.ssoDomainVerification?.status === SsoDomainVerificationStatus.VERIFIED),
}
},
})
@@ -329,7 +330,7 @@ export type SignInMethods = {
}
type GetSignInMethodsParams = {
- platform: Pick<PlatformWithoutSensitiveData, 'emailAuthEnabled' | 'googleAuthEnabled' | 'federatedAuthProviders'>
+ platform: Pick<Platform | PlatformWithoutSensitiveData, 'emailAuthEnabled' | 'googleAuthEnabled' | 'federatedAuthProviders' | 'ssoDomainVerification'>
}
type GetOnboardingResponseParams = {
diff --git a/packages/server/api/src/app/platform/platform.service.ts b/packages/server/api/src/app/platform/platform.service.ts
index c19f45d2ff6..b2b73e009b1 100644
--- a/packages/server/api/src/app/platform/platform.service.ts
+++ b/packages/server/api/src/app/platform/platform.service.ts
@@ -226,9 +226,12 @@ export const platformService = (log: FastifyBaseLogger) => ({
}
log.info({ platform: { id: params.id } }, 'Platform updated')
const { saved, locked } = await transaction(async (entityManager) => {
- const lockedPlatform = await lockPlatformForUpdate({ entityManager, platformId: params.id, includeFederatedAuth: hasFederatedAuth(platform) })
+ const lockedPlatform = await lockPlatformForUpdate({ entityManager, platformId: params.id, includeFederatedAuth: true })
+ const signInSettingsToSave = buildSignInSettingsToSave({ lockedPlatform, params })
+ assertLeavesAWorkingSignInMethod({ log, before: lockedPlatform, after: signInSettingsToSave })
const savedPlatform = await platformRepo(entityManager).save({
...updatedPlatform,
+ ...signInSettingsToSave,
auditLogRetentionDays: params.auditLogRetentionDays === undefined ? lockedPlatform.auditLogRetentionDays ?? null : params.auditLogRetentionDays,
})
return { saved: savedPlatform, locked: lockedPlatform }
@@ -514,6 +517,30 @@ async function assertAuditLogRetentionDaysAllowed({ log, platform, auditLogReten
}
}
+function buildSignInSettingsToSave({ lockedPlatform, params }: BuildSignInSettingsToSaveParams): SignInSettings {
+ return {
+ emailAuthEnabled: params.emailAuthEnabled ?? lockedPlatform.emailAuthEnabled,
+ googleAuthEnabled: params.googleAuthEnabled ?? lockedPlatform.googleAuthEnabled,
+ ssoDomainVerification: params.ssoDomainVerification === undefined ? lockedPlatform.ssoDomainVerification : params.ssoDomainVerification,
+ federatedAuthProviders: { ...lockedPlatform.federatedAuthProviders, ...params.federatedAuthProviders },
+ }
+}
+
+function assertLeavesAWorkingSignInMethod({ log, before, after }: AssertLeavesAWorkingSignInMethodParams): void {
+ const methodsBefore = authenticationUtils(log).getSignInMethods({ platform: before })
+ const methodsAfter = authenticationUtils(log).getSignInMethods({ platform: after })
+ const hadWorkingMethod = methodsBefore.email || methodsBefore.google || methodsBefore.sso
+ const hasWorkingMethod = methodsAfter.email || methodsAfter.google || methodsAfter.sso
+ if (hadWorkingMethod && !hasWorkingMethod) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: {
+ message: 'This is the only way left to sign in. Turn on another sign-in method first.',
+ },
+ })
+ }
+}
+
async function getPlan(log: FastifyBaseLogger, platform: PlatformWithoutFederatedAuth): Promise<PlatformPlanLimits> {
const edition = system.getEdition()
if (edition === ApEdition.COMMUNITY) {
@@ -562,6 +589,19 @@ type AssertAuditLogRetentionDaysAllowedParams = {
auditLogRetentionDays: number | null | undefined
}
+type SignInSettings = Pick<Platform, 'emailAuthEnabled' | 'googleAuthEnabled' | 'ssoDomainVerification' | 'federatedAuthProviders'>
+
+type BuildSignInSettingsToSaveParams = {
+ lockedPlatform: Platform
+ params: UpdateParams
+}
+
+type AssertLeavesAWorkingSignInMethodParams = {
+ log: FastifyBaseLogger
+ before: SignInSettings
+ after: SignInSettings
+}
+
type LockPlatformForUpdateParams = {
entityManager: EntityManager
platformId: PlatformId
diff --git a/packages/server/api/test/integration/ce/platform/last-sign-in-method.test.ts b/packages/server/api/test/integration/ce/platform/last-sign-in-method.test.ts
new file mode 100644
index 00000000000..d133c2b1451
--- /dev/null
+++ b/packages/server/api/test/integration/ce/platform/last-sign-in-method.test.ts
@@ -0,0 +1,24 @@
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { createTestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('Last sign-in method guard on CE', () => {
+ it('allows turning email off, because CE always counts email as working', async () => {
+ const ctx = await createTestContext(app, { platform: { emailAuthEnabled: true, googleAuthEnabled: false } })
+
+ const response = await ctx.post(`/v1/platforms/${ctx.platform.id}`, { emailAuthEnabled: false })
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ })
+})
diff --git a/packages/server/api/test/integration/cloud/audit-event/authentication-audit-events.test.ts b/packages/server/api/test/integration/cloud/audit-event/authentication-audit-events.test.ts
index da6b15c04a2..21693e000f9 100644
--- a/packages/server/api/test/integration/cloud/audit-event/authentication-audit-events.test.ts
+++ b/packages/server/api/test/integration/cloud/audit-event/authentication-audit-events.test.ts
@@ -10,9 +10,13 @@ let app: FastifyInstance | null = null
beforeAll(async () => {
app = await setupTestEnvironment()
+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'
+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'
})
afterAll(async () => {
+ delete process.env.AP_GOOGLE_CLIENT_ID
+ delete process.env.AP_GOOGLE_CLIENT_SECRET
await teardownTestEnvironment()
})
diff --git a/packages/server/api/test/integration/cloud/platform/last-sign-in-method.test.ts b/packages/server/api/test/integration/cloud/platform/last-sign-in-method.test.ts
new file mode 100644
index 00000000000..54686d34d55
--- /dev/null
+++ b/packages/server/api/test/integration/cloud/platform/last-sign-in-method.test.ts
@@ -0,0 +1,147 @@
+import { Platform, SsoDomainVerification, SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { platformRepo } from '../../../../src/app/platform/platform.service'
+import { createTestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterEach(() => {
+ delete process.env.AP_GOOGLE_CLIENT_ID
+ delete process.env.AP_GOOGLE_CLIENT_SECRET
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('Last sign-in method guard on Cloud', () => {
+ it.each([
+ {
+ reason: 'turning email off when it is the only method',
+ platform: { emailAuthEnabled: true, googleAuthEnabled: false },
+ googleKeys: false,
+ path: 'platform',
+ body: { emailAuthEnabled: false },
+ },
+ {
+ reason: 'turning email off when Google is on but the server has no Google keys',
+ platform: { emailAuthEnabled: true, googleAuthEnabled: true },
+ googleKeys: false,
+ path: 'platform',
+ body: { emailAuthEnabled: false },
+ },
+ {
+ reason: 'turning Google off when it is the only method',
+ platform: { emailAuthEnabled: false, googleAuthEnabled: true },
+ googleKeys: true,
+ path: 'platform',
+ body: { googleAuthEnabled: false },
+ },
+ {
+ reason: 'disabling SSO when it is the only method',
+ platform: { emailAuthEnabled: false, googleAuthEnabled: false },
+ ssoDomain: 'disable-sso.example.com',
+ googleKeys: false,
+ path: 'platform',
+ body: { federatedAuthProviders: { saml: null } },
+ },
+ {
+ reason: 'removing the domain when SSO is the only method',
+ platform: { emailAuthEnabled: false, googleAuthEnabled: false },
+ ssoDomain: 'remove-domain.example.com',
+ googleKeys: false,
+ path: 'sso-domain',
+ body: { ssoDomain: null },
+ },
+ {
+ reason: 'changing the domain when SSO is the only method',
+ platform: { emailAuthEnabled: false, googleAuthEnabled: false },
+ ssoDomain: 'change-domain.example.com',
+ googleKeys: false,
+ path: 'sso-domain',
+ body: { ssoDomain: 'changed-domain.example.com' },
+ },
+ ])('refuses $reason', async ({ platform, ssoDomain, googleKeys, path, body }) => {
+ setGoogleKeys({ configured: googleKeys })
+ const ctx = await createTestContext(app, { platform: { ...platform, ...ssoOn({ domain: ssoDomain }) }, plan: { ssoEnabled: true } })
+ const before = await readSignInSettings({ platformId: ctx.platform.id })
+
+ const response = await ctx.post(path === 'platform' ? `/v1/platforms/${ctx.platform.id}` : SSO_DOMAIN, body)
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response.json()).toEqual(expect.objectContaining({ code: 'VALIDATION', params: { message: LAST_METHOD_MESSAGE } }))
+ expect(await readSignInSettings({ platformId: ctx.platform.id })).toEqual(before)
+ })
+
+ it.each([
+ {
+ reason: 'turning email off while Google still works',
+ platform: { emailAuthEnabled: true, googleAuthEnabled: true },
+ googleKeys: true,
+ body: { emailAuthEnabled: false },
+ },
+ {
+ reason: 'renaming a platform that already has no working method',
+ platform: { emailAuthEnabled: false, googleAuthEnabled: false },
+ googleKeys: false,
+ body: { name: 'Renamed platform' },
+ },
+ ])('allows $reason', async ({ platform, googleKeys, body }) => {
+ setGoogleKeys({ configured: googleKeys })
+ const ctx = await createTestContext(app, { platform, plan: { ssoEnabled: true } })
+
+ const response = await ctx.post(`/v1/platforms/${ctx.platform.id}`, body)
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ })
+
+})
+
+function setGoogleKeys({ configured }: { configured: boolean }): void {
+ if (configured) {
+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'
+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'
+ }
+}
+
+function ssoOn({ domain }: { domain: string | undefined }): SsoOnSettings | Record<string, never> {
+ if (domain === undefined) {
+ return {}
+ }
+ return {
+ ssoDomain: domain,
+ ssoDomainVerification: {
+ status: SsoDomainVerificationStatus.VERIFIED,
+ record: { type: SsoDomainVerificationRecordType.TXT, name: `_activepieces-verify.${domain}`, value: 'activepieces-verify=test-token' },
+ createdAt: new Date().toISOString(),
+ },
+ federatedAuthProviders: { saml: SAML },
+ }
+}
+
+async function readSignInSettings({ platformId }: { platformId: string }): Promise<SignInSettings> {
+ return platformRepo().findOneOrFail({
+ where: { id: platformId },
+ select: { id: true, emailAuthEnabled: true, googleAuthEnabled: true, ssoDomain: true, ssoDomainVerification: true, federatedAuthProviders: true },
+ })
+}
+
+const SSO_DOMAIN = '/v1/authn/saml/sso-domain'
+
+const LAST_METHOD_MESSAGE = 'This is the only way left to sign in. Turn on another sign-in method first.'
+
+const SAML = { idpMetadata: '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"></md:EntityDescriptor>', idpCertificate: 'test-cert' }
+
+type SsoOnSettings = {
+ ssoDomain: string
+ ssoDomainVerification: SsoDomainVerification
+ federatedAuthProviders: { saml: typeof SAML }
+}
+
+type SignInSettings = Pick<Platform, 'id' | 'emailAuthEnabled' | 'googleAuthEnabled' | 'ssoDomain' | 'ssoDomainVerification' | 'federatedAuthProviders'>
diff --git a/packages/server/api/test/integration/cloud/platform/platform.test.ts b/packages/server/api/test/integration/cloud/platform/platform.test.ts
index 412f03db703..3046f9f8a9c 100644
--- a/packages/server/api/test/integration/cloud/platform/platform.test.ts
+++ b/packages/server/api/test/integration/cloud/platform/platform.test.ts
@@ -41,9 +41,13 @@ function deletionJobIds(platformId: string) {
beforeAll(async () => {
app = await setupTestEnvironment()
+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'
+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'
})
afterAll(async () => {
+ delete process.env.AP_GOOGLE_CLIENT_ID
+ delete process.env.AP_GOOGLE_CLIENT_SECRET
await teardownTestEnvironment()
})
describe('Platform API', () => {
diff --git a/packages/server/api/test/integration/ee/platform/last-sign-in-method.test.ts b/packages/server/api/test/integration/ee/platform/last-sign-in-method.test.ts
new file mode 100644
index 00000000000..d537cec4291
--- /dev/null
+++ b/packages/server/api/test/integration/ee/platform/last-sign-in-method.test.ts
@@ -0,0 +1,92 @@
+import { Platform, SsoDomainVerification, SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { platformRepo } from '../../../../src/app/platform/platform.service'
+import { createTestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('Last sign-in method guard on self-hosted EE', () => {
+ it.each([
+ {
+ reason: 'disabling SSO when it is the only method, even with the domain still pending',
+ domain: 'ee-disable-sso.example.com',
+ status: SsoDomainVerificationStatus.PENDING_VERIFICATION,
+ path: 'platform',
+ body: { federatedAuthProviders: { saml: null } },
+ },
+ {
+ reason: 'removing a verified domain when SSO is the only method, because it also deletes SAML',
+ domain: 'ee-remove-domain.example.com',
+ status: SsoDomainVerificationStatus.VERIFIED,
+ path: 'sso-domain',
+ body: { ssoDomain: null },
+ },
+ ])('refuses $reason', async ({ domain, status, path, body }) => {
+ const ctx = await createTestContext(app, { platform: onlySso({ domain, status }), plan: { ssoEnabled: true } })
+ const before = await readSignInSettings({ platformId: ctx.platform.id })
+
+ const response = await ctx.post(path === 'platform' ? `/v1/platforms/${ctx.platform.id}` : SSO_DOMAIN, body)
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response.json()).toEqual(expect.objectContaining({ code: 'VALIDATION', params: { message: LAST_METHOD_MESSAGE } }))
+ expect(await readSignInSettings({ platformId: ctx.platform.id })).toEqual(before)
+ })
+
+ it('allows changing the domain when SSO is the only method, because EE does not check the domain at sign-in', async () => {
+ const ctx = await createTestContext(app, {
+ platform: onlySso({ domain: 'ee-change-domain.example.com', status: SsoDomainVerificationStatus.VERIFIED }),
+ plan: { ssoEnabled: true },
+ })
+
+ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: 'ee-changed-domain.example.com' })
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ })
+})
+
+function onlySso({ domain, status }: { domain: string, status: SsoDomainVerificationStatus }): OnlySsoPlatform {
+ return {
+ emailAuthEnabled: false,
+ googleAuthEnabled: false,
+ ssoDomain: domain,
+ ssoDomainVerification: {
+ status,
+ record: { type: SsoDomainVerificationRecordType.TXT, name: `_activepieces-verify.${domain}`, value: 'activepieces-verify=test-token' },
+ createdAt: new Date().toISOString(),
+ },
+ federatedAuthProviders: { saml: SAML },
+ }
+}
+
+async function readSignInSettings({ platformId }: { platformId: string }): Promise<SignInSettings> {
+ return platformRepo().findOneOrFail({
+ where: { id: platformId },
+ select: { id: true, emailAuthEnabled: true, googleAuthEnabled: true, ssoDomain: true, ssoDomainVerification: true, federatedAuthProviders: true },
+ })
+}
+
+const SSO_DOMAIN = '/v1/authn/saml/sso-domain'
+
+const LAST_METHOD_MESSAGE = 'This is the only way left to sign in. Turn on another sign-in method first.'
+
+const SAML = { idpMetadata: '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"></md:EntityDescriptor>', idpCertificate: 'test-cert' }
+
+type OnlySsoPlatform = {
+ emailAuthEnabled: boolean
+ googleAuthEnabled: boolean
+ ssoDomain: string
+ ssoDomainVerification: SsoDomainVerification
+ federatedAuthProviders: { saml: typeof SAML }
+}
+
+type SignInSettings = Pick<Platform, 'id' | 'emailAuthEnabled' | 'googleAuthEnabled' | 'ssoDomain' | 'ssoDomainVerification' | 'federatedAuthProviders'>
diff --git a/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts b/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts
index 464ac8db2fd..e3f3668ee6b 100644
--- a/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts
+++ b/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts
@@ -22,6 +22,7 @@ describe('SSO domain API', () => {
const ctx = await createTestContext(app!, {
plan: { ssoEnabled: true },
platform: {
+ emailAuthEnabled: true,
ssoDomain: 'remove-with-saml.example.com',
ssoDomainVerification: verified('remove-with-saml.example.com'),
federatedAuthProviders: { saml: SAML },