: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): catch a wrong JSON key file before the API rejects it (#94956)
Tom Owers8a82a9784312
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 6192f0cb891b..07a77ec6ebb2 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -266,6 +266,32 @@ function webhookResultHasNoPendingInputs(webhookResult: WebhookCreateResult | nu// than the status code itself, so don't let it stand in for a message the source wrote.const GENERIC_SERVER_ERROR_DETAIL = 'A server error occurred.'+// A wrong-but-valid JSON file (a client config instead of a service account key, say) parses+// fine, so the API is left rejecting it by naming its own config fields. Check the keys the+// source declared while the file is still in hand.+export function missingUploadedFileKeys(parsed: unknown, keys: '*' | string[]): string[] {+ if (keys === '*') {+ return []+ }+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return [...keys]+ }+ const record = parsed as Record<string, unknown>+ return keys.filter((key) => record[key] === undefined || record[key] === null || record[key] === '')+}++// Carries the failed submit out of the form without the outer handler mistaking it for an API+// error; the toast has already said what to do, so nothing else reports it.+export class UnusableUploadedFileError extends Error {+ constructor(fieldName: string) {+ super(`Uploaded "${fieldName}" file is missing the keys this source requires`)+ this.name = 'UnusableUploadedFileError'+ }+}++export const WRONG_UPLOADED_FILE_MESSAGE =+ 'This JSON file is missing the fields PostHog needs. Upload the key file exactly as it was generated, without editing its contents.'+export function resolveConnectErrorMessage(e: any): string {const detail = e?.detail === GENERIC_SERVER_ERROR_DETAIL ? undefined : e?.detailconst apiMessage = e?.data?.message ?? detail@@ -3934,14 +3960,16 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([const payloadKeys = (values.selectedConnector?.fields ?? []).map((n) => ({name: n.name,type: n.type,+ fileKeys: n.type === 'file-upload' ? n.fileFormat.keys : ([] as string[]),}))const fieldPayload: Record<string, any> = {source_type: values.selectedConnector.name,}- for (const { name, type } of payloadKeys) {+ for (const { name, type, fileKeys } of payloadKeys) {if (type === 'file-upload') {+ let parsedFile: unknowntry {// Assumes we're loading a JSON fileconst loadedFile: string = await new Promise((resolve, reject) => {@@ -3951,13 +3979,21 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([reject(fileReader.error ?? new Error(`Failed to read the "${name}" file`))fileReader.readAsText(payload['payload'][name][0])})- fieldPayload[name] = JSON.parse(loadedFile)+ parsedFile = JSON.parse(loadedFile)} catch (e: any) {posthog.captureException(e)- return lemonToast.error(+ 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]}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.tsindex 9fbb90e80463..115ebd1cbdc1 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.ts@@ -1,7 +1,7 @@import type { SourceFieldConfig } from '~/queries/schema/schema-general'import { findOauthBranch, normalizeMultiValue } from '../../shared/components/forms/IntegrationAccountSelector'-import { getErrorsForFields } from './sourceWizardLogic'+import { getErrorsForFields, missingUploadedFileKeys } from './sourceWizardLogic'const REPOSITORIES_FIELD: SourceFieldConfig = {type: 'oauth-account-select',@@ -114,4 +114,24 @@ describe('source wizard multi-value fields', () => {expect(normalizeMultiValue(value, legacy)).toEqual(expected)})})+ describe('missingUploadedFileKeys', () => {+ const SERVICE_ACCOUNT_KEYS = ['project_id', 'private_key', 'client_email']++ // Uploading the wrong JSON is the common mistake here: it parses, so the only thing that+ // catches it is the declared key list.+ it.each([+ [{ project_id: 'p', private_key: 'k', client_email: 'e' }, []],+ [{ project_info: { project_id: 'p' } }, SERVICE_ACCOUNT_KEYS],+ [{ project_id: 'p', private_key: '', client_email: 'e' }, ['private_key']],+ [{ project_id: 'p', private_key: null, client_email: 'e' }, ['private_key']],+ [[{ project_id: 'p' }], SERVICE_ACCOUNT_KEYS],+ ['not an object', SERVICE_ACCOUNT_KEYS],+ ])('reports %p as missing %p', (parsed, expected) => {+ expect(missingUploadedFileKeys(parsed, SERVICE_ACCOUNT_KEYS)).toEqual(expected)+ })++ it('accepts any shape when the source declares no specific keys', () => {+ expect(missingUploadedFileKeys({ anything: true }, '*')).toEqual([])+ })+ })})