: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): validate uploaded file against selected format before upload (#80282)
Tom Owers7c19fd346953
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.test.tsnew file mode 100644index 000000000000..6b538bc521d0--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.test.ts@@ -0,0 +1,35 @@+import { FileUploadFormat } from './fileUploadSource'+import { fileFormatMismatchError, fileUploadFormErrors } from './fileUploadSourceLogic'++describe('file upload format validation', () => {+ it.each<[string, FileUploadFormat]>([+ ['data.xlsx', 'csv'],+ ['data.xls', 'json'],+ ['report.numbers', 'parquet'],+ ])('rejects spreadsheet file %s regardless of selected format', (filename, format) => {+ expect(fileFormatMismatchError(filename, format)).toContain('Spreadsheet files')+ })++ it('flags a file whose extension belongs to a different supported format', () => {+ expect(fileFormatMismatchError('events.json', 'csv')).toContain('looks like a JSON file')+ })++ it.each<[string, FileUploadFormat]>([+ ['events.csv', 'csv'],+ ['events.ndjson', 'json'],+ ['events.parquet', 'parquet'],+ ])('accepts %s when the matching format is selected', (filename, format) => {+ expect(fileFormatMismatchError(filename, format)).toBeUndefined()+ })++ it('leaves an unrecognized extension alone so a valid file is not blocked', () => {+ // A CSV exported as .txt is still parseable; we only block confident mismatches.+ expect(fileFormatMismatchError('export.txt', 'csv')).toBeUndefined()+ })++ it('surfaces the mismatch as a files error so submission is blocked', () => {+ const file = new File(['a,b'], 'sheet.xlsx')+ const errors = fileUploadFormErrors({ files: [file], table_name: 'my_table', file_format: 'csv' })+ expect(errors.files).toContain('Spreadsheet files')+ })+})diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsxindex 591942fe8ec3..22faa65b521f 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx@@ -21,6 +21,48 @@ export const FILE_UPLOAD_ACCEPT: Record<FileUploadFormat, string> = {parquet: '.parquet',}+const FORMAT_LABELS: Record<FileUploadFormat, string> = {+ csv: 'CSV',+ json: 'JSON',+ parquet: 'Parquet',+}++// Extensions we can confidently map to a supported format. Anything not listed (e.g. .txt) is left+// alone so a validly-formatted file with an unusual extension isn't blocked.+const EXTENSION_FORMATS: Record<string, FileUploadFormat> = {+ csv: 'csv',+ json: 'json',+ ndjson: 'json',+ jsonl: 'json',+ parquet: 'parquet',+ pqt: 'parquet',+}++const SPREADSHEET_EXTENSIONS = new Set(['xlsx', 'xls', 'xlsm', 'xlsb', 'ods', 'numbers'])++function fileExtension(filename: string): string {+ const match = /\.([^.]+)$/.exec(filename.toLowerCase())+ return match ? match[1] : ''+}++// The `accept` attribute only hints the file picker; a mismatched file can still be dragged in or+// left selected after switching format. Catch the confident cases here so the user gets clear+// guidance instead of an opaque column-read failure after a wasted upload round-trip.+export function fileFormatMismatchError(filename: string, format: FileUploadFormat): string | undefined {+ const ext = fileExtension(filename)+ if (!ext) {+ return undefined+ }+ if (SPREADSHEET_EXTENSIONS.has(ext)) {+ return "Spreadsheet files like Excel can't be uploaded directly. Export to CSV, JSON, or Parquet first, then upload that."+ }+ const extFormat = EXTENSION_FORMATS[ext]+ if (extFormat && extFormat !== format) {+ return `This looks like a ${FORMAT_LABELS[extFormat]} file, but you selected the ${FORMAT_LABELS[format]} format. Set the format to ${FORMAT_LABELS[extFormat]}, or choose a ${FORMAT_LABELS[format]} file.`+ }+ return undefined+}+const HOGQL_TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/export interface FileUploadForm {@@ -46,14 +88,20 @@ export function parseFileUploadFormat(value: string | undefined): FileUploadFormreturn normalized === 'csv' || normalized === 'json' || normalized === 'parquet' ? normalized : null}-export function fileUploadFormErrors({ files, table_name }: Partial<FileUploadForm>): Record<string, unknown> {+export function fileUploadFormErrors({+ files,+ table_name,+ file_format,+}: Partial<FileUploadForm>): Record<string, unknown> {const file = files?.[0]return {files: !file? 'Please choose a file to upload.': file.size > MAX_FILE_UPLOAD_SIZE_BYTES? 'This file is larger than 50MB. For bigger files, connect the bucket they live in as a self-managed source instead.'- : undefined,+ : file_format+ ? fileFormatMismatchError(file.name, file_format)+ : undefined,table_name: !table_name? 'Please enter a table name.': !HOGQL_TABLE_NAME_REGEX.test(table_name)@@ -172,6 +220,11 @@ export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([lemonToast.error('This file is larger than the 50MB upload limit.')return}+ const formatMismatch = fileFormatMismatchError(file.name, file_format)+ if (formatMismatch) {+ lemonToast.error(formatMismatch)+ return+ }const formData = new FormData()formData.append('file', file)