Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

13.9 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'

import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'

import { IntegrationType } from '~/types'

/**
 * The `aws-redshift` integration kind covers three backend classes, told apart only by which config
 * keys the create request carries: `aws_role_arn` picks the role-based one, an access key pair picks
 * the credentials one, and host/port/user/password picks the plain Postgres-wire one. Each mode
 * below must send exactly its own keys, or the wrong class handles the request.
 */
export type RedshiftAuthMode = 'role' | 'access_key' | 'password'

// Partition suffixes (aws-cn, aws-us-gov) are allowed, matching AWS_ROLE_ARN_RE on the backend.
const IAM_ROLE_ARN_REGEX = /^arn:aws(-[a-z-]+)?:iam::\d{12}:role\/.+$/
const SERVERLESS_WORKGROUP_ARN_REGEX = /^arn:aws(-[a-z-]+)?:redshift-serverless:[a-z0-9-]+:\d{12}:workgroup\/.+$/

export interface RedshiftSetupModalLogicProps {
    isOpen: boolean
    integration?: IntegrationType | null
    onComplete: (integrationId?: number) => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface redshiftSetupModalLogicValues {
    authMode: RedshiftAuthMode
    isRedshiftIntegrationSubmitting: boolean
    isRedshiftIntegrationValid: boolean
    redshiftIntegration: {
        autoCreate: boolean
        awsAccessKeyId: string
        awsRoleArn: string
        awsSecretAccessKey: string
        groups: string[]
        host: string
        name: string
        password: string
        port: number
        sslMode: string
        sslRootCert: string
        user: string
        useSystemCa: boolean
        workgroupArn: string
    }
    redshiftIntegrationAllErrors: Record<string, any>
    redshiftIntegrationChanged: boolean
    redshiftIntegrationErrors: DeepPartialMap<
        {
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        },
        ValidationErrorType
    >
    redshiftIntegrationHasErrors: boolean
    redshiftIntegrationManualErrors: Record<string, any>
    redshiftIntegrationTouched: boolean
    redshiftIntegrationTouches: Record<string, boolean>
    redshiftIntegrationValidationErrors: DeepPartialMap<
        {
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        },
        ValidationErrorType
    >
    showRedshiftIntegrationErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface redshiftSetupModalLogicActions {
    loadIntegrations: (_?: any) => any // integrationsLogic
    resetRedshiftIntegration: (values?: {
        autoCreate: boolean
        awsAccessKeyId: string
        awsRoleArn: string
        awsSecretAccessKey: string
        groups: string[]
        host: string
        name: string
        password: string
        port: number
        sslMode: string
        sslRootCert: string
        user: string
        useSystemCa: boolean
        workgroupArn: string
    }) => {
        values?: {
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        }
    }
    setAuthMode: (mode: RedshiftAuthMode) => {
        mode: RedshiftAuthMode
    }
    setRedshiftIntegrationManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setRedshiftIntegrationValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setRedshiftIntegrationValues: (
        values: DeepPartial<{
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        }>
    ) => {
        values: DeepPartial<{
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        }>
    }
    submitRedshiftIntegration: () => {
        value: boolean
    }
    submitRedshiftIntegrationFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitRedshiftIntegrationRequest: (redshiftIntegration: {
        autoCreate: boolean
        awsAccessKeyId: string
        awsRoleArn: string
        awsSecretAccessKey: string
        groups: string[]
        host: string
        name: string
        password: string
        port: number
        sslMode: string
        sslRootCert: string
        user: string
        useSystemCa: boolean
        workgroupArn: string
    }) => {
        redshiftIntegration: {
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        }
    }
    submitRedshiftIntegrationSuccess: (redshiftIntegration: {
        autoCreate: boolean
        awsAccessKeyId: string
        awsRoleArn: string
        awsSecretAccessKey: string
        groups: string[]
        host: string
        name: string
        password: string
        port: number
        sslMode: string
        sslRootCert: string
        user: string
        useSystemCa: boolean
        workgroupArn: string
    }) => {
        redshiftIntegration: {
            autoCreate: boolean
            awsAccessKeyId: string
            awsRoleArn: string
            awsSecretAccessKey: string
            groups: string[]
            host: string
            name: string
            password: string
            port: number
            sslMode: string
            sslRootCert: string
            user: string
            useSystemCa: boolean
            workgroupArn: string
        }
    }
    touchRedshiftIntegrationField: (key: string) => {
        key: string
    }
}

export type redshiftSetupModalLogicType = MakeLogicType<
    redshiftSetupModalLogicValues,
    redshiftSetupModalLogicActions,
    RedshiftSetupModalLogicProps
>

export const redshiftSetupModalLogic = kea<redshiftSetupModalLogicType>([
    path(['integrations', 'redshift', 'redshiftSetupModalLogic']),
    props({} as RedshiftSetupModalLogicProps),
    connect(() => ({
        actions: [integrationsLogic, ['loadIntegrations']],
    })),
    actions({
        setAuthMode: (mode: RedshiftAuthMode) => ({ mode }),
    }),
    reducers({
        authMode: [
            'role' as RedshiftAuthMode,
            {
                setAuthMode: (_, { mode }) => mode,
            },
        ],
    }),
    forms(({ props, actions, values }) => ({
        redshiftIntegration: {
            defaults: {
                name: '',
                user: '',
                awsRoleArn: '',
                awsAccessKeyId: '',
                awsSecretAccessKey: '',
                groups: [] as string[],
                autoCreate: false as boolean,
                workgroupArn: '',
                host: '',
                port: 5439,
                password: '',
                sslMode: 'require',
                useSystemCa: true as boolean,
                sslRootCert: '',
            },
            errors: ({
                name,
                user,
                awsRoleArn,
                awsAccessKeyId,
                awsSecretAccessKey,
                workgroupArn,
                host,
                port,
                password,
                sslMode,
                useSystemCa,
                sslRootCert,
            }) => {
                const isAws = values.authMode !== 'password'
                return {
                    name: !isAws || name.trim() ? undefined : 'Name is required',
                    user: user.trim() ? undefined : 'User is required',
                    awsRoleArn:
                        values.authMode !== 'role'
                            ? undefined
                            : !awsRoleArn.trim()
                              ? 'IAM role ARN is required'
                              : !IAM_ROLE_ARN_REGEX.test(awsRoleArn.trim())
                                ? 'Enter a valid IAM role ARN, e.g. arn:aws:iam::123456789012:role/my-role'
                                : undefined,
                    awsAccessKeyId:
                        values.authMode !== 'access_key' || awsAccessKeyId.trim()
                            ? undefined
                            : 'Access key ID is required',
                    awsSecretAccessKey:
                        values.authMode !== 'access_key' || awsSecretAccessKey.trim()
                            ? undefined
                            : 'Secret access key is required',
                    workgroupArn:
                        !isAws || !workgroupArn.trim() || SERVERLESS_WORKGROUP_ARN_REGEX.test(workgroupArn.trim())
                            ? undefined
                            : 'Enter a valid workgroup ARN, e.g. arn:aws:redshift-serverless:us-east-1:123456789012:workgroup/my-workgroup',
                    host: isAws || host.trim() ? undefined : 'Host is required',
                    port: isAws || port ? undefined : 'Port is required',
                    password: isAws || password.trim() ? undefined : 'Password is required',
                    sslRootCert:
                        isAws || sslMode === 'require' || useSystemCa || sslRootCert.trim()
                            ? undefined
                            : 'Upload a root certificate, or use the system certificate authorities',
                }
            },
            submit: async () => {
                const {
                    name,
                    user,
                    awsRoleArn,
                    awsAccessKeyId,
                    awsSecretAccessKey,
                    groups,
                    autoCreate,
                    workgroupArn,
                    host,
                    port,
                    password,
                    sslMode,
                    useSystemCa,
                    sslRootCert,
                } = values.redshiftIntegration

                const awsConfig = {
                    name,
                    user: user.trim(),
                    auto_create: autoCreate,
                    ...(groups.length ? { groups } : {}),
                    ...(workgroupArn.trim() ? { workgroup_arn: workgroupArn.trim() } : {}),
                }

                const config =
                    values.authMode === 'role'
                        ? { ...awsConfig, aws_role_arn: awsRoleArn.trim() }
                        : values.authMode === 'access_key'
                          ? {
                                ...awsConfig,
                                aws_access_key_id: awsAccessKeyId.trim(),
                                aws_secret_access_key: awsSecretAccessKey,
                            }
                          : {
                                host: host.trim(),
                                port,
                                user: user.trim(),
                                password,
                                ssl_mode: sslMode,
                                ...(sslMode !== 'require'
                                    ? { ssl_root_cert: useSystemCa ? 'system' : sslRootCert }
                                    : {}),
                            }

                try {
                    const integration = await api.integrations.create({ kind: 'aws-redshift', config })
                    actions.loadIntegrations()
                    lemonToast.success('Redshift connection created')
                    props.onComplete(integration.id)
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to create the Redshift connection')
                    throw error
                }
            },
        },
    })),
    listeners(({ actions }) => ({
        setAuthMode: () => {
            actions.setRedshiftIntegrationValues({
                awsRoleArn: '',
                awsAccessKeyId: '',
                awsSecretAccessKey: '',
                password: '',
                sslRootCert: '',
            })
        },
    })),
])