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

11.3 KB
Raw Blame
import { resolveTxt } from 'dns/promises'
import { ActivepiecesError, apId, assertNotNullOrUndefined, ErrorCode, isNil, PlatformId, spreadIfDefined, tryCatch, UserId } from '@activepieces/core-utils'
import { ApEdition, SAMLAuthnProviderConfig, SsoDomainVerification, SsoDomainVerificationRecordType, SsoDomainVerificationStatus, UserIdentityProvider } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { AuthenticationResult } from '../../../authentication/authentication-utils'
import { authenticationService } from '../../../authentication/authentication.service'
import { domainHelper } from '../../../helper/domain-helper'
import { system } from '../../../helper/system/system'
import { platformSideEffects } from '../../../platform/platform-side-effects'
import { platformRepo, platformService } from '../../../platform/platform.service'
import { platformUtils } from '../../../platform/platform.utils'
import { platformPlanService } from '../../platform/platform-plan/platform-plan.service'
import { createSamlClient, IdpLoginResponse } from './saml-client'

export const authnSsoSamlService = (log: FastifyBaseLogger) => {
    return {
        async getAcsUrl(platformId: string): Promise<string> {
            const baseUrl = await domainHelper.getPublicApiUrl({ path: '/v1/authn/saml/acs' })
            if (system.getEdition() === ApEdition.CLOUD) {
                // we still want to support entreprise customers who are still using custom domains . without forcing them to change their saml redirect url
                const legacyHost = await platformUtils.getLegacyHostByPlatformId(platformId)
                if (legacyHost) {
                    return `https://${legacyHost}/api/v1/authn/saml/acs`
                }
                return `${baseUrl}?platformId=${encodeURIComponent(platformId)}`
            }
            return baseUrl
        },
        async getSamlConfigOrThrow(platformId: string | null): Promise<SamlConfigResult> {
            assertNotNullOrUndefined(platformId, 'Platform ID is required for SAML authentication')
            const platform = await platformService(log).getOneWithFederatedAuthOrThrow(platformId)
            const saml = platform.federatedAuthProviders.saml
            assertNotNullOrUndefined(saml, 'SAML IDP metadata is not configured for this platform')
            return { saml, platformId }
        },
        async login(platformId: string, samlProvider: SAMLAuthnProviderConfig): Promise<LoginResponse> {
            const acsUrl = await this.getAcsUrl(platformId)

            const client = await createSamlClient({ platformId, samlProvider, acsUrl })
            const redirectUrl = client.getLoginUrl()
            return {
                redirectUrl,
            }
        },
        async acs(platformId: string, samlProvider: SAMLAuthnProviderConfig, idpLoginResponse: IdpLoginResponse): Promise<AuthenticationResult> {
            const acsUrl = await this.getAcsUrl(platformId)
            const client = await createSamlClient({ platformId, samlProvider, acsUrl })
            const attributes = await client.parseAndValidateLoginResponse(idpLoginResponse)
            return authenticationService(log).federatedAuthn({
                email: attributes.email,
                firstName: attributes.firstName,
                lastName: attributes.lastName,
                newsLetter: false,
                trackEvents: true,
                provider: UserIdentityProvider.SAML,
                predefinedPlatformId: platformId,
            })
        },
        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 null
            }
            const platform = await platformRepo().findOneBy({ ssoDomain })
            if (isNil(platform) || platform.ssoDomainVerification?.status !== SsoDomainVerificationStatus.VERIFIED) {
                return null
            }
            const plan = await platformPlanService(log).getOrCreateForPlatform(platform.id)
            return plan.ssoEnabled ? platform.id : null
        },
        async updateSsoDomain({ platformId, ssoDomain, userId, ip }: UpdateSsoDomainParams): Promise<SsoDomainState> {
            const normalized = ssoDomain?.trim().toLowerCase() ?? null
            const value = normalized && normalized.length > 0 ? normalized : null
            if (!isNil(value)) {
                if (!z.hostname().safeParse(value).success || !value.includes('.')) {
                    throw new ActivepiecesError({
                        code: ErrorCode.VALIDATION,
                        params: {
                            message: 'SSO domain must be a valid lowercase domain (e.g. acme.com)',
                        },
                    })
                }
                const existing = await platformRepo().findOneBy({ ssoDomain: value })
                if (!isNil(existing) && existing.id !== platformId) {
                    throw new ActivepiecesError({
                        code: ErrorCode.VALIDATION,
                        params: {
                            message: 'This SSO domain is already in use',
                        },
                    })
                }
            }

            const current = await platformService(log).getOneOrThrow(platformId)
            const verification = computeNextVerification({ nextDomain: value, currentDomain: current.ssoDomain ?? null, currentVerification: current.ssoDomainVerification ?? null })

            const removesVerifiedDomain = isNil(value) && current.ssoDomainVerification?.status === SsoDomainVerificationStatus.VERIFIED
            const removesSaml = removesVerifiedDomain && await platformService(log).hasSamlConfigured(platformId)
            await platformService(log).update({
                id: platformId,
                ssoDomain: value,
                ssoDomainVerification: verification,
                ...spreadIfDefined('federatedAuthProviders', removesSaml ? { saml: null } : undefined),
                userId,
                ip,
            })
            return { ssoDomain: value, ssoDomainVerification: verification }
        },
        async verifySsoDomain({ platformId, userId, ip }: VerifySsoDomainParams): Promise<SsoDomainState> {
            const platform = await platformService(log).getOneOrThrow(platformId)
            if (isNil(platform.ssoDomain) || isNil(platform.ssoDomainVerification)) {
                throw new ActivepiecesError({
                    code: ErrorCode.VALIDATION,
                    params: {
                        message: 'No SSO domain configured for this platform',
                    },
                })
            }
            if (platform.ssoDomainVerification.status === SsoDomainVerificationStatus.VERIFIED) {
                return { ssoDomain: platform.ssoDomain, ssoDomainVerification: platform.ssoDomainVerification }
            }

            const matched = await txtRecordMatches({ name: platform.ssoDomainVerification.record.name, expected: platform.ssoDomainVerification.record.value, log })
            if (!matched) {
                return { ssoDomain: platform.ssoDomain, ssoDomainVerification: platform.ssoDomainVerification }
            }

            const verified: SsoDomainVerification = {
                ...platform.ssoDomainVerification,
                status: SsoDomainVerificationStatus.VERIFIED,
            }
            const updated = await platformService(log).update({ id: platformId, ssoDomainVerification: verified, userId, ip })
            return { ssoDomain: updated.ssoDomain ?? null, ssoDomainVerification: updated.ssoDomainVerification ?? null }
        },
        async expirePendingSsoDomains(): Promise<void> {
            const rows: unknown = await platformRepo().query(`
                WITH expired AS (
                    SELECT id, "ssoDomain" FROM "platform"
                    WHERE "ssoDomain" IS NOT NULL
                      AND "ssoDomainVerification"->>'status' = $1
                      AND ("ssoDomainVerification"->>'createdAt')::timestamptz < NOW() - make_interval(days => $2)
                    FOR UPDATE SKIP LOCKED
                ), cleared AS (
                    UPDATE "platform" p
                    SET "ssoDomain" = NULL, "ssoDomainVerification" = NULL
                    FROM expired
                    WHERE p.id = expired.id
                    RETURNING p.id AS "platformId", expired."ssoDomain" AS "domain"
                )
                SELECT "platformId", "domain" FROM cleared
            `, [SsoDomainVerificationStatus.PENDING_VERIFICATION, PENDING_DOMAIN_TTL_DAYS])
            const expired = ExpiredSsoDomainRows.parse(rows)
            for (const { platformId, domain } of expired) {
                platformSideEffects(log).onSsoDomainExpired({ platformId, domain })
            }
            if (expired.length > 0) {
                log.info({ affected: expired.length }, 'Expired pending SSO domain verifications')
            }
        },
    }
}

const PENDING_DOMAIN_TTL_DAYS = 7

const ExpiredSsoDomainRows = z.array(z.object({
    platformId: z.string(),
    domain: z.string(),
}))

function computeNextVerification({ nextDomain, currentDomain, currentVerification }: { nextDomain: string | null, currentDomain: string | null, currentVerification: SsoDomainVerification | null }): SsoDomainVerification | null {
    if (isNil(nextDomain)) {
        return null
    }
    if (nextDomain === currentDomain && !isNil(currentVerification)) {
        return currentVerification
    }
    return {
        status: SsoDomainVerificationStatus.PENDING_VERIFICATION,
        record: {
            type: SsoDomainVerificationRecordType.TXT,
            name: `${VERIFICATION_NAME_PREFIX}.${nextDomain}`,
            value: `${VERIFICATION_VALUE_PREFIX}=${apId()}`,
        },
        createdAt: new Date().toISOString(),
    }
}

async function txtRecordMatches({ name, expected, log }: { name: string, expected: string, log: FastifyBaseLogger }): Promise<boolean> {
    const lookup = await tryCatch(() => resolveTxt(name))
    if (lookup.error) {
        log.warn({ name, error: lookup.error }, 'TXT record lookup failed for SSO domain verification')
        return false
    }
    return lookup.data.some((chunks) => chunks.join('').trim() === expected)
}

const VERIFICATION_NAME_PREFIX = '_activepieces-verify'
const VERIFICATION_VALUE_PREFIX = 'activepieces-verify'

type LoginResponse = {
    redirectUrl: string
}

type SamlConfigResult = {
    saml: SAMLAuthnProviderConfig
    platformId: string
}

type DiscoverResult = {
    platformId: string | null
}

type FindPlatformIdByDomainParams = {
    domain: string
}

type UpdateSsoDomainParams = {
    platformId: PlatformId
    ssoDomain: string | null
    userId: UserId
    ip: string
}

type VerifySsoDomainParams = {
    platformId: PlatformId
    userId: UserId
    ip: string
}

type SsoDomainState = {
    ssoDomain: string | null
    ssoDomainVerification: SsoDomainVerification | null
}