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.

fix(warehouse-sources): parse uploaded key files nested in a select option (#104497)

posthog[bot]579f22a4a32d
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index ce275ff50a73..8f60eae4f782 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -53,6 +53,7 @@ import {
} from '../../shared/components/forms/schemaGroupingUtils'
import type { WebhookCreateResult } from '../../shared/components/forms/WebhookSetupForm'
import { sourceManagementLogic } from '../../shared/logics/sourceManagementLogic'
+import { clonePayloadPreservingFiles, findUploadedFiles, readJsonFile } from '../../shared/sourceFieldFiles'
import { shouldShowDestinationStep } from './components/destinationStepUtils'
import { FILE_UPLOAD_SOURCE_CONFIG, FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'
import { selfManagedSourceLogic } from './selfManagedSourceLogic'
@@ -2662,46 +2663,38 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
await api.externalDataSources.source_prefix(payload.source_type, sourceValues.prefix)
}
- const payloadKeys = (values.selectedConnector?.fields ?? []).map((n) => ({
- name: n.name,
- type: n.type,
- fileKeys: n.type === 'file-upload' ? n.fileFormat.keys : ([] as string[]),
- }))
+ const formPayload = clonePayloadPreservingFiles(payload['payload'] ?? {}) as Record<string, any>
+
+ for (const { field, container, file } of findUploadedFiles(
+ values.selectedConnector?.fields ?? [],
+ formPayload
+ )) {
+ let parsedFile: unknown
+ try {
+ // Assumes we're loading a JSON file
+ parsedFile = await readJsonFile(file)
+ } catch (e: any) {
+ posthog.captureException(e)
+ lemonToast.error(
+ `The "${field.name}" file is not valid — it must be a readable JSON file.`
+ )
+ // Returning here would resolve the submit, so the wizard would go
+ // on to discover schemas for a source it never updated.
+ throw e
+ }
+ if (missingUploadedFileKeys(parsedFile, field.fileFormat.keys).length > 0) {
+ lemonToast.error(WRONG_UPLOADED_FILE_MESSAGE)
+ throw new UnusableUploadedFileError(field.name)
+ }
+ container[field.name] = parsedFile
+ }
const fieldPayload: Record<string, any> = {
source_type: values.selectedConnector.name,
}
- for (const { name, type, fileKeys } of payloadKeys) {
- if (type === 'file-upload') {
- let parsedFile: unknown
- try {
- // Assumes we're loading a JSON file
- const loadedFile: string = await new Promise((resolve, reject) => {
- const fileReader = new FileReader()
- fileReader.onload = (e) => resolve(e.target?.result as string)
- fileReader.onerror = () =>
- reject(fileReader.error ?? new Error(`Failed to read the "${name}" file`))
- fileReader.readAsText(payload['payload'][name][0])
- })
- parsedFile = JSON.parse(loadedFile)
- } catch (e: any) {
- posthog.captureException(e)
- lemonToast.error(
- `The "${name}" file is not valid — it must be a readable JSON file.`
- )
- // Returning here would resolve the submit, so the wizard would go
- // on to discover schemas for a source it never updated.
- throw e
- }
- if (missingUploadedFileKeys(parsedFile, fileKeys).length > 0) {
- lemonToast.error(WRONG_UPLOADED_FILE_MESSAGE)
- throw new UnusableUploadedFileError(name)
- }
- fieldPayload[name] = parsedFile
- } else {
- fieldPayload[name] = payload['payload'][name]
- }
+ for (const field of values.selectedConnector?.fields ?? []) {
+ fieldPayload[field.name] = formPayload[field.name]
}
// Include CDC configuration if present
@@ -2716,8 +2709,8 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
'cdc_lag_critical_threshold_mb',
]
for (const key of cdcKeys) {
- if (payload['payload']?.[key] !== undefined) {
- cdcFields[key] = payload['payload'][key]
+ if (formPayload[key] !== undefined) {
+ cdcFields[key] = formPayload[key]
}
}
diff --git a/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx
index 8528b4aa71f1..96c654ef1264 100644
--- a/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx
@@ -11,6 +11,11 @@ import { urls } from 'scenes/urls'
import { ApiConfig } from '~/lib/api'
import { Breadcrumb } from '~/types'
+import {
+ clonePayloadPreservingFiles,
+ findUploadedFiles,
+ readJsonFile,
+} from 'products/data_warehouse/frontend/shared/sourceFieldFiles'
import type { SourceFieldConfig } from 'products/data_warehouse/frontend/types'
import { externalDataSourcesStoreCredentialsCreate } from 'products/warehouse_sources/frontend/generated/api'
import { SourceConfigResponseApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
@@ -36,24 +41,14 @@ const buildCredentialsPayload = async (
): Promise<Record<string, any>> => {
const payload: Record<string, any> = {}
for (const field of fields) {
- const value = formPayload[field.name]
- if (field.type === 'file-upload') {
- if (value?.[0]) {
- try {
- // Assumes we're loading a JSON file, same as the wizard's submit
- const loadedFile: string = await new Promise((resolve, reject) => {
- const fileReader = new FileReader()
- fileReader.onload = (e) => resolve(e.target?.result as string)
- fileReader.onerror = (e) => reject(e)
- fileReader.readAsText(value[0])
- })
- payload[field.name] = JSON.parse(loadedFile)
- } catch (e) {
- throw new FileUploadParseError(field.name, e)
- }
- }
- } else {
- payload[field.name] = value
+ payload[field.name] = clonePayloadPreservingFiles(formPayload[field.name])
+ }
+ for (const { field, container, file } of findUploadedFiles(fields, payload)) {
+ try {
+ // Assumes we're loading a JSON file, same as the wizard's submit
+ container[field.name] = await readJsonFile(file)
+ } catch (e) {
+ throw new FileUploadParseError(field.name, e)
}
}
return payload
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
index c7c92951ba2a..045c596913d5 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
@@ -6,7 +6,6 @@ import { clampSyncFrequency } from 'products/data_warehouse/frontend/utils'
import {
buildBulkEnablePayloads,
bulkSyncMethodDisabledReason,
- clonePayloadPreservingFiles,
effectiveLookbackDays,
isSensitiveCredentialField,
removeEmptySensitiveValues,
@@ -197,25 +196,6 @@ describe('removeEmptySensitiveValues', () => {
})
})
-describe('clonePayloadPreservingFiles', () => {
- it('preserves File instances in nested payloads', () => {
- const keyFile = new File(['{"project_id":"my-project"}'], 'service-account.json', {
- type: 'application/json',
- })
- const payload = {
- key_file: [keyFile],
- config: { use_custom_region: { enabled: true, region: 'us-east1' } },
- }
-
- const cloned = clonePayloadPreservingFiles(payload) as Record<string, any>
-
- expect(cloned).not.toBe(payload)
- expect(cloned.config).not.toBe(payload.config)
- expect(cloned.key_file[0]).toBeInstanceOf(File)
- expect(cloned.key_file[0]).toBe(keyFile)
- })
-})
-
describe('schemasEligibleForSync', () => {
it('keeps only schemas that are enabled with a sync method', () => {
const schemas = [
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index 96e4849b10e4..d0e64cae7215 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -36,6 +36,11 @@ import {
} from '~/types'
import { groupTablesBySchema } from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'
+import {
+ clonePayloadPreservingFiles,
+ findUploadedFiles,
+ readJsonFile,
+} from 'products/data_warehouse/frontend/shared/sourceFieldFiles'
import type { SourceFieldConfig } from 'products/data_warehouse/frontend/types'
import { SYNC_FREQUENCY_ORDER, SyncTypeLabelMap, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'
import { SourceConfigResponseApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
@@ -298,30 +303,6 @@ export const removeEmptySensitiveValues = (fields: SourceFieldConfig[], valueObj
}
}
-export const clonePayloadPreservingFiles = (value: unknown): unknown => {
- if (value instanceof File) {
- return value
- }
-
- if (Array.isArray(value)) {
- return value.map((item) => clonePayloadPreservingFiles(item))
- }
-
- if (value instanceof Date) {
- return new Date(value.getTime())
- }
- if (value && typeof value === 'object' && value.constructor === Object) {
- return Object.fromEntries(
- Object.entries(value as Record<string, unknown>).map(([key, nestedValue]) => [
- key,
- clonePayloadPreservingFiles(nestedValue),
- ])
- )
- }
-
- return value
-}
-
// Run a per-schema API action across many schemas; returns how many failed.
export async function runBulkSchemaAction(
schemas: ExternalDataSourceSchema[],
@@ -1104,16 +1085,18 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
auto_sync_new_schemas,
auto_sync_schema_patterns,
}) => {
+ const captureSaveOutcome = (outcome: string): void => {
+ posthog.capture('warehouse source saved', {
+ source_type: values.source?.source_type,
+ outcome,
+ })
+ }
+
const sanitizedPayload = clonePayloadPreservingFiles(payload) as Record<string, any>
if (values.sourceFieldConfig?.fields) {
removeEmptySensitiveValues(values.sourceFieldConfig.fields, sanitizedPayload)
}
- const newJobInputs = {
- ...values.source?.job_inputs,
- ...sanitizedPayload,
- }
-
// Read before the update, while `values.source` still holds the old config, so we can
// offer a resync when the user widens the history window (otherwise it's silently ignored).
const previousLookbackDays = effectiveLookbackDays(values.source?.job_inputs?.[SYNC_LOOKBACK_FIELD])
@@ -1121,30 +1104,26 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
const schemasToResync = schemasNeedingLookbackResync(values.source)
// Handle file uploads
- const sourceFieldConfig = values.sourceFieldConfig
- if (sourceFieldConfig?.fields) {
- for (const field of sourceFieldConfig.fields) {
- if (field.type === 'file-upload' && sanitizedPayload[field.name]) {
- try {
- // Assumes we're loading a JSON file
- const loadedFile: string = await new Promise((resolve, reject) => {
- const fileReader = new FileReader()
- fileReader.onload = (e) => resolve(e.target?.result as string)
- fileReader.onerror = (e) => reject(e)
- fileReader.readAsText(sanitizedPayload[field.name][0])
- })
- newJobInputs[field.name] = JSON.parse(loadedFile)
- } catch (e: any) {
- posthog.captureException(e)
- lemonToast.error(
- `The "${field.name}" file is not valid — it must be a readable JSON file.`
- )
- return
- }
- }
+ for (const { field, container, file } of findUploadedFiles(
+ values.sourceFieldConfig?.fields ?? [],
+ sanitizedPayload
+ )) {
+ try {
+ // Assumes we're loading a JSON file
+ container[field.name] = await readJsonFile(file)
+ } catch (e: any) {
+ posthog.captureException(e)
+ captureSaveOutcome('file_unreadable')
+ lemonToast.error(`The "${field.name}" file is not valid — it must be a readable JSON file.`)
+ return
}
}
+ const newJobInputs = {
+ ...values.source?.job_inputs,
+ ...sanitizedPayload,
+ }
+
try {
await sourcesDataLogic.asyncActions.updateSource({
...values.source!,
@@ -1166,6 +1145,7 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
description: description !== '' ? description : (values.source?.description ?? null),
})
actions.loadSource()
+ captureSaveOutcome('success')
lemonToast.success('Source updated')
if (nextLookbackDays > previousLookbackDays && schemasToResync.length > 0) {
@@ -1186,6 +1166,7 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
: undefined,
})
} catch (e: any) {
+ captureSaveOutcome('rejected')
if (e.message) {
lemonToast.error(e.message)
} else {
diff --git a/products/data_warehouse/frontend/shared/sourceFieldFiles.test.ts b/products/data_warehouse/frontend/shared/sourceFieldFiles.test.ts
new file mode 100644
index 000000000000..52451ef555a4
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/sourceFieldFiles.test.ts
@@ -0,0 +1,124 @@
+import type { SourceFieldConfig } from 'products/data_warehouse/frontend/types'
+
+import { clonePayloadPreservingFiles, findUploadedFiles } from './sourceFieldFiles'
+
+const KEY_FILE_FIELD: SourceFieldConfig = {
+ type: 'file-upload',
+ name: 'key_file',
+ label: 'JSON key file',
+ required: false,
+ fileFormat: { format: '.json', keys: ['project_id'] },
+}
+
+const AUTH_TYPE_FIELD: SourceFieldConfig = {
+ type: 'select',
+ name: 'auth_type',
+ label: 'Authentication type',
+ required: true,
+ defaultValue: 'service_account',
+ options: [
+ {
+ label: 'Google Cloud service account',
+ value: 'service_account',
+ fields: [
+ {
+ type: 'oauth',
+ name: 'google_cloud_service_account_integration_id',
+ label: 'Google Cloud service account',
+ required: false,
+ kind: 'google-cloud-service-account',
+ },
+ ],
+ },
+ { label: 'JSON key file', value: 'key_file', fields: [KEY_FILE_FIELD] },
+ ],
+}
+
+function makeKeyFile(): File {
+ return new File(['{"project_id":"my-project"}'], 'service-account.json', { type: 'application/json' })
+}
+
+describe('sourceFieldFiles', () => {
+ describe('findUploadedFiles', () => {
+ it('finds a file a select option nests under the parent field', () => {
+ const keyFile = makeKeyFile()
+ const payload = { auth_type: { selection: 'key_file', key_file: [keyFile] } }
+
+ const uploads = findUploadedFiles([AUTH_TYPE_FIELD], payload)
+
+ expect(uploads).toHaveLength(1)
+ expect(uploads[0].file).toBe(keyFile)
+ expect(uploads[0].container).toBe(payload.auth_type)
+ })
+
+ it('finds a file a switch group nests under the parent field', () => {
+ const keyFile = makeKeyFile()
+ const fields: SourceFieldConfig[] = [
+ {
+ type: 'switch-group',
+ name: 'credentials',
+ label: 'Use a key file?',
+ default: false,
+ fields: [KEY_FILE_FIELD],
+ },
+ ]
+ const payload = { credentials: { enabled: true, key_file: [keyFile] } }
+
+ expect(findUploadedFiles(fields, payload)).toEqual([
+ { field: KEY_FILE_FIELD, container: payload.credentials, file: keyFile },
+ ])
+ })
+
+ it.each([[false], ['False']])('skips a file in a switch group disabled with %s', (enabled) => {
+ const fields: SourceFieldConfig[] = [
+ {
+ type: 'switch-group',
+ name: 'credentials',
+ label: 'Use a key file?',
+ default: false,
+ fields: [KEY_FILE_FIELD],
+ },
+ ]
+
+ expect(findUploadedFiles(fields, { credentials: { enabled, key_file: [makeKeyFile()] } })).toEqual([])
+ })
+
+ it('finds a file at the top of the payload', () => {
+ const keyFile = makeKeyFile()
+
+ expect(findUploadedFiles([KEY_FILE_FIELD], { key_file: [keyFile] })).toHaveLength(1)
+ })
+
+ it('skips the option the user did not pick', () => {
+ const payload = { auth_type: { selection: 'service_account', key_file: [makeKeyFile()] } }
+
+ expect(findUploadedFiles([AUTH_TYPE_FIELD], payload)).toEqual([])
+ })
+
+ it.each([
+ ['nothing picked', {}],
+ ['an earlier upload the form seeded back in', { project_id: 'my-project' }],
+ ])('skips a field holding %s', (_, keyFileValue) => {
+ const payload = { auth_type: { selection: 'key_file', key_file: keyFileValue } }
+
+ expect(findUploadedFiles([AUTH_TYPE_FIELD], payload)).toEqual([])
+ })
+ })
+
+ describe('clonePayloadPreservingFiles', () => {
+ it('preserves File instances in nested payloads', () => {
+ const keyFile = makeKeyFile()
+ const payload = {
+ key_file: [keyFile],
+ config: { use_custom_region: { enabled: true, region: 'us-east1' } },
+ }
+
+ const cloned = clonePayloadPreservingFiles(payload) as Record<string, any>
+
+ expect(cloned).not.toBe(payload)
+ expect(cloned.config).not.toBe(payload.config)
+ expect(cloned.key_file[0]).toBeInstanceOf(File)
+ expect(cloned.key_file[0]).toBe(keyFile)
+ })
+ })
+})
diff --git a/products/data_warehouse/frontend/shared/sourceFieldFiles.ts b/products/data_warehouse/frontend/shared/sourceFieldFiles.ts
new file mode 100644
index 000000000000..fbae0f47061a
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/sourceFieldFiles.ts
@@ -0,0 +1,87 @@
+import { getTextFromFile } from 'lib/utils/file-utils'
+
+import type { SourceFieldConfig } from 'products/data_warehouse/frontend/types'
+
+type FileUploadField = Extract<SourceFieldConfig, { type: 'file-upload' }>
+
+export interface UploadedFileField {
+ field: FileUploadField
+ /** The object the field's value sits on, so the caller can write the parsed file back to it. */
+ container: Record<string, any>
+ /** The file the user picked. */
+ file: File
+}
+
+export const clonePayloadPreservingFiles = (value: unknown): unknown => {
+ if (value instanceof File) {
+ return value
+ }
+
+ if (Array.isArray(value)) {
+ return value.map((item) => clonePayloadPreservingFiles(item))
+ }
+
+ if (value instanceof Date) {
+ return new Date(value.getTime())
+ }
+ if (value && typeof value === 'object' && value.constructor === Object) {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([key, nestedValue]) => [
+ key,
+ clonePayloadPreservingFiles(nestedValue),
+ ])
+ )
+ }
+
+ return value
+}
+
+/**
+ * Every file the user picked, with the object its value sits on. A file-upload field declared
+ * inside a select option or a switch group renders in a kea `Group`, so its value lands under the
+ * parent field's name (`auth_type.key_file`) rather than at the top of the payload.
+ *
+ * A field whose value is not a fresh `File` is left out: on the configuration form the stored,
+ * already-parsed contents of an earlier upload sit under the same name.
+ */
+export const findUploadedFiles = (fields: SourceFieldConfig[], valueObj: Record<string, any>): UploadedFileField[] => {
+ const uploads: UploadedFileField[] = []
+
+ for (const field of fields) {
+ if (field.type === 'file-upload') {
+ const file = valueObj[field.name]?.[0]
+ if (file instanceof File) {
+ uploads.push({ field, container: valueObj, file })
+ }
+ continue
+ }
+
+ const nestedValue = valueObj[field.name]
+ const canDescend = !!nestedValue && typeof nestedValue === 'object' && !Array.isArray(nestedValue)
+
+ // A disabled group's stored file must not be sent; the backend string form comes from an
+ // earlier config, the same as the form validation handles.
+ const groupEnabled = canDescend && !!nestedValue.enabled && nestedValue.enabled !== 'False'
+
+ if (field.type === 'switch-group' && groupEnabled) {
+ uploads.push(...findUploadedFiles(field.fields, nestedValue))
+ continue
+ }
+
+ if (field.type === 'select' && canDescend) {
+ const selection = nestedValue.selection ?? field.defaultValue
+ const selectedFields = field.options.find((option) => option.value === selection)?.fields ?? []
+ uploads.push(...findUploadedFiles(selectedFields, nestedValue))
+ }
+ }
+
+ return uploads
+}
+
+export const readJsonFile = async (file: File): Promise<Record<string, unknown>> => {
+ const parsed: unknown = JSON.parse(await getTextFromFile(file))
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('The uploaded JSON file must contain an object')
+ }
+ return parsed as Record<string, unknown>
+}