Skip to content

Neutralize spreadsheet formulas in CSV exports - #36070

Merged
sonika-shah merged 9 commits into
mainfrom
fix/csv-export-formula-injection
Nov 3, 2026
Merged

sonika-shah merged 9 commits into
mainfrom
fix/csv-export-formula-injection

Conversation

@sonika-shah

@sonika-shah sonika-shah commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes open-metadata/openmetadata-collate#7803

Summary

Exported CSVs wrote user-controlled cells verbatim, so a value such as =HYPERLINK(...) in a description was evaluated as a formula when the export was opened in a spreadsheet.

Fix: cells starting with =, +, -, @, tab or CR are prefixed with ' on export, in the REST export response itself. Import removes exactly that quote, so export → edit → re-import round-trips unchanged. The rule is recorded in docs/decisions/2026-10-30-entity-csv-export-escapes-formula-cells-and-import-restores-them.md.

What changed

  • CsvUtil.formatCsv (the export path for all entity/lineage exports) escapes formula cells via neutralizeFormula; both EntityCsv.parse overloads reverse it via restoreFormula.
  • Recursive database-service and drive-service exports restore the nested child export's cells before formatting again, so each cell is escaped once.
  • UI Bulk Edit grid: strips the escape when it loads a CSV and re-adds it when it builds the CSV for import (restoreFormula / neutralizeFormula in CSVPureUtils.ts, same rule as the server), so users see stored values.
  • Tests: EntityCsvTest (unit), DatabaseServiceResourceIT.test_importExportRecursive_escapesFormulaCellsOnce (nested export + round trip; fails without the fix), CSVPureUtils.test.ts (UI helpers).
Details
  • Only the first character is checked, so quoted dotted names like "local.mysql".default (start with ") and user:x;team:y lists are untouched. Field-level escaping (;, ,, quotes) happens before and is reversed after, so it is unaffected.
  • A value already shaped like an escaped one (e.g. '=x) gets one more quote on export, so every value comes back exactly. Negative numbers and markdown bullets (- item) round-trip too.
  • Without the nested-export fix, a schema under a database service exported as '''=already quoted and lost data on re-import; the new IT covers that.
  • Behaviour change for API consumers: scripts reading the export endpoint see '-5 where the stored value is -5. A hand-written import cell starting with ' + trigger loses that one quote.
  • Ran: CSV unit tests in openmetadata-service (183) green; DatabaseServiceResourceIT recursive import/export ITs (5) green; CSVPureUtils.test.ts (20) and BulkEntityImportPage.test.tsx (37) green. Earlier: dotted-service-name round-trip ITs in DatabaseResourceIT green.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; the previous apostrophe-loss issue is fixed.

Summary

Protects formula-like CSV cells on export and restores their original values on import.

  • CSV exports keep formula-like values from running in spreadsheets.

Reviews (2) · Last reviewed commit: "Keep values already shaped like an escap..." · Reviewed by Greptile


Summary by Gitar

  • Sample data download:
    • Escapes formula-like cells in SampleDataTable.utils.ts with FORMULA_LIKE to match entity exports
  • Lineage CSV export:
    • Neutralizes formula cells in LineageRepository async exports
  • Recursive export:
    • Restores nested child cells in DatabaseServiceRepository and DriveServiceRepository so each cell is escaped once
  • Documentation:
    • Adds ADR describing the formula-escape and restore rule

This will update automatically on new commits.

Cells starting with = + - @ tab or CR are prefixed with a quote on export so a
spreadsheet shows them as text instead of evaluating them. Import strips the
quote again, so an exported file re-imports unchanged.
@sonika-shah
sonika-shah requested a review from a team as a code owner October 23, 2026 08:05
@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • Linked issue open-metadata/openmetadata-collate#7803 does not exist or is not accessible.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Oct 23, 2026
A value such as "'=x" was exported unchanged and then lost its quote on
import. Such values now get one more quote on export, so import returns every
value exactly. Tests cover quoted dotted FQNs, which are left untouched.
…id raw

Recursive database- and drive-service exports re-read the already escaped
child export and formatted it again, so nested cells gained a second quote
and kept one after re-import. Restore those cells before re-adding them.

The Bulk Edit grid loads the export response directly, so it now strips the
escape when it loads a CSV and adds it back when it builds the CSV for
import, with the same rule as CsvUtil. Records the escaping contract in
docs/decisions.
@sonika-shah
sonika-shah requested a review from a team as a code owner October 30, 2026 06:01
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ UI Checkstyle passed — lint findings in changed files

🔍 ESLint findings in this PR's files — 0 error(s), 6 warning(s)

Errors block the build. Warnings do not yet — they are rules whose backlog is still
being worked down, listed so this PR does not add to it. See docs/ui-code-quality-gate.md.

0 error(s), 6 warning(s) across 2 changed file(s).

Count Rule
3 react-hooks/exhaustive-deps
2 openmetadata-imports/no-impure-pure-utils
1 openmetadata-imports/no-cross-page-imports
All findings
Location Rule Message
🟡 src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:143:1 openmetadata-imports/no-cross-page-imports Page features must not import another page feature. Move shared code to components, hooks, interfaces, or pure utilities.
🟡 src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:875:5 react-hooks/exhaustive-deps React Hook useCallback has an unnecessary dependency: 'entityType'. Either exclude it or remove the dependency array.
🟡 src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:1375:6 react-hooks/exhaustive-deps React Hook useEffect has missing dependencies: 'handleImportWebsocketResponse' and 'handleResetImportJob'. Either include them or remove the dependency array.
🟡 src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:1466:6 react-hooks/exhaustive-deps React Hook useMemo has a missing dependency: 'filterColumns'. Either include it or remove the dependency array.
🟡 src/utils/CSV/CSVPureUtils.ts:16:1 openmetadata-imports/no-impure-pure-utils Pure utilities must not depend on React, UI, state, hooks, pages, or REST clients. Move orchestration/rendering out or move shared types to a lower layer.
🟡 src/utils/CSV/CSVPureUtils.ts:17:1 openmetadata-imports/no-impure-pure-utils Pure utilities must not depend on React, UI, state, hooks, pages, or REST clients. Move orchestration/rendering out or move shared types to a lower layer.

Fix locally (fast - only checks files changed in this branch):

make ui-checkstyle-changed

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 81%
80.93% (136927/169171) 67.83% (49124/72421) 70.89% (27670/39028)

The import result echoes parsed (unescaped) cells, while the submitted CSV
now carries the formula escape, so rows with cells like '- bullet' were never
highlighted as failed.
Copilot AI balanced review requested due to automatic review settings November 2, 2026 04:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Both async lineage export routes bypass formula neutralization in their shared CSV writer, leaving malicious pipeline descriptions executable as spreadsheet formulas in downloaded CSVs.

1 open issue
What changed in this PR

This PR adds reversible formula escaping to OpenMetadata’s shared CSV export/import flow, protecting spreadsheet users while preserving stored values across round trips.

Changes:

  • Prefix formula-like cells on export and remove one escape quote on import.
  • Restore nested exports before reformatting and apply the same rule in the Bulk Edit grid.
  • Add Java and UI regression coverage and document the CSV contract.
File Description
openmetadata-ui/​src/​main/​resources/​ui/​src/​utils/​CSV/​CSVPureUtils.ts Adds escape/restore helpers and normalizes failed-row matching.
openmetadata-ui/​src/​main/​resources/​ui/​src/​utils/​CSV/​CSVPureUtils.test.ts Tests formula round trips, grid serialization, and failed-row matching.
openmetadata-ui/​src/​main/​resources/​ui/​src/​pages/​EntityImport/​BulkEntityImportPage/​BulkEntityImportPage.tsx Restores escaped cells when loading the grid.
openmetadata-service/​src/​test/​java/​org/​openmetadata/​csv/​EntityCsvTest.java Tests export escaping and both import parsers.
openmetadata-service/​src/​main/​java/​org/​openmetadata/​service/​jdbi3/​DriveServiceRepository.java Prevents double escaping in recursive drive exports.
openmetadata-service/​src/​main/​java/​org/​openmetadata/​service/​jdbi3/​DatabaseServiceRepository.java Prevents double escaping in recursive database exports.
openmetadata-service/​src/​main/​java/​org/​openmetadata/​csv/​EntityCsv.java Restores escaped values in both parse overloads.
openmetadata-service/​src/​main/​java/​org/​openmetadata/​csv/​CsvUtil.java Escapes formula-like cells in the shared formatter.
openmetadata-integration-tests/​src/​test/​java/​org/​openmetadata/​it/​tests/​DatabaseServiceResourceIT.java Tests recursive export escaping and import round trips.
docs/​decisions/​2026-10-30-entity-csv-export-escapes-formula-cells-and-import-restores-them.md Records the escaping contract and compatibility implications.

Review effort: Balanced

exportCsvAsync and exportByEntityCountCsvAsync write rows through
writeCsvRow, which bypassed CsvUtil.formatCsv, so a pipeline description
such as =HYPERLINK(...) reached the downloaded CSV unescaped. Apply
CsvUtil.neutralizeFormula to every cell in that shared writer. Lineage
CSV is export-only, so no import-side restore is needed.
Copilot AI balanced review requested due to automatic review settings November 2, 2026 04:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the CSV formula-injection protection changes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@yan-3005 yan-3005 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of other CSV outputs don't go through formatCsv, so they don't get the new escaping:

  • Ontology release export (GET /v1/ontologyReleases/{id}/export as text/csv): OntologyReleaseExporter → NativeOntologyCsvCodec.write → NativeOntologyCsvWriter.print writes the label, description and other cells as they are. Running them through CsvUtil.neutralizeFormula would cover it; NativeOntologyCsvCodec.read would then need restoreFormula so re-importing an exported file still round-trips.
  • SPARQL results as CSV (POST /v1/ontologies/{id}/sparql): OntologySparqlQueryService hands the result set to Jena's ResultSetFormatter.outputAsCSV, which writes literals raw as well.

The search export already has its own check in SearchResultCsvExporter.escapeCsv, but it doesn't treat a leading tab or CR as a trigger the way CsvUtil now does. Might be worth pointing it at neutralizeFormula so there's one rule.

Happy for these to be a follow-up if you'd rather keep this PR to the entity exports.

@sonika-shah

Copy link
Copy Markdown
Collaborator Author

@yan-3005 Thanks. These are outside what this PR covers (entity CSV exports). On the details: the search export already strips leading whitespace, including tab and CR, before checking, so it's covered. For SPARQL, the API returns the standard results format that clients parse, so any escaping belongs in the console's Download button rather than the API. I'll raise the SPARQL download and the ontology release export as a follow-up.

@sonika-shah
sonika-shah enabled auto-merge November 2, 2026 06:39
@harsh-vador

Copy link
Copy Markdown
Contributor

One more export path this doesn't cover: the sample data download. buildSampleDataCSVContent in SampleDataTable.utils.ts builds the CSV with unparse and no formula escaping. Those values come straight from the source database, so they're probably the easiest place to plant a =HYPERLINK(...).

KnowledgeGraph.tsx already does unparse(..., { escapeFormulae: true }). Passing escapeFormulae: /^'*[=+\-@\t\r]/ there would match the rule in this PR. It's a one-line change, so could it go in here? If you'd rather keep this PR focused on entity exports, a follow-up issue is fine too.

Copilot AI balanced review requested due to automatic review settings November 2, 2026 06:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@sonika-shah

Copy link
Copy Markdown
Collaborator Author

@harshach Sample data download is in 02baffc: buildSampleDataCSVContent now passes escapeFormulae with the same rule, exported from CSVPureUtils.ts as FORMULA_LIKE so there is one pattern, plus a test in SampleDataTable.utils.test.ts.

@sonika-shah
sonika-shah added this pull request to the merge queue Nov 2, 2026
@sonika-shah
sonika-shah removed this pull request from the merge queue due to a manual request Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-11-02T10:44:39Z)

The entry left the queue before it was built, so no checks ran against it.

…a-injection

# Conflicts:
#	openmetadata-ui/src/main/resources/ui/src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx
#	openmetadata-ui/src/main/resources/ui/src/utils/CSV/CSVPureUtils.test.ts
Copilot AI balanced review requested due to automatic review settings November 2, 2026 10:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@sonika-shah
sonika-shah enabled auto-merge November 2, 2026 10:51
@gitar-bot

gitar-bot Bot commented Nov 2, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 4 closed / 4 findings

🔴 High risk · Prefixing formula-like cells across REST CSV exports changes their public values, which could break clients expecting raw stored values.

Neutralizes spreadsheet formula cells in CSV exports by prefixing =, +, -, @, tab and CR values with ', with import restoring them so round-trips are lossless. Resolved the round-trip alteration of values already shaped like escapes, the Bulk Edit grid now showing the escape, the missing ADR for the escaping contract, and failed-row highlighting for formula-like cells. No open issues found.

✅ 4 closed
✅ Edge Case: Values that already start with '=, '-, etc. are altered on round-trip

📄 openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java:76-90
neutralizeFormula leaves a value like '-5 or '=x unchanged, because its first character is ', which isn't a trigger. On import, restoreFormula then strips that quote, so the stored value silently becomes -5 / =x. This contradicts the PR's claim that export → re-import round-trips unchanged, and the same thing happens to hand-written import files with such a value. Fix it by also escaping values that restoreFormula would change: prefix them with a second ' on export, and on import strip one ' from any value matching ^'+[=+\-@ \r].

✅ Bug: Bulk Edit grid now shows the ' escape in exported values

📄 openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java:66 📄 openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java:76-78
The UI Bulk Edit page loads the export API response straight into its grid (readString(csvExportData, …) in BulkEditEntity.component.tsx:311), not through a spreadsheet. Since formatCsv now prefixes every cell that starts with =, +, -, @, tab or CR, users will see and edit values like '- item for markdown bullet descriptions, '-2 for negative custom-property numbers and '+1 …. Typed cell editors may also reject these values. The server restores them on import, but the grid is the main in-product consumer of this response, and it now gets values nobody wrote. Either strip the escape where the UI hydrates the grid (the same rule as restoreFormula), or apply the neutralization only to file downloads (the UI's downloadCsv / an export option) and leave the API payload the grid reads unchanged.

✅ Quality: New CSV cell-escaping contract isn't recorded in docs/decisions

📄 openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java:50-51 📄 openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java:72-86 📄 openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java:983 📄 openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java:1014
This PR adds a format that other components must agree on: the UI bulk-edit grid, external scripts reading the REST export, and anything that builds import files. The rule exists only in the PR description and isn't in docs/decisions/; the only CSV record there covers the UTF-8 BOM. The record would state: "Exported CSV cells whose first character is =, +, -, @, tab or CR are prefixed with '; import strips a leading ' only when it is followed by one of those characters" (from the description: "cells starting with =, +, -, @, tab or CR are prefixed with ' on export. Import strips that prefix again" and "Only a leading ' followed by a trigger character is stripped on import"). It should also say whether the REST payload or only downloaded files carry the escape.

✅ Bug: Failed-row highlighting misses rows that contain formula-like cells

📄 openmetadata-ui/src/main/resources/ui/src/utils/CSV/CSVPureUtils.ts:339 📄 openmetadata-ui/src/main/resources/ui/src/utils/CSV/CSVPureUtils.ts:479 📄 openmetadata-ui/src/main/resources/ui/src/utils/CSV/CSVPureUtils.ts:485 📄 openmetadata-ui/src/main/resources/ui/src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:802
getCSVStringFromColumnsAndDataSource now escapes cells, so validatedSubmission.csv holds values like '- bullet or '-5. The server echoes rows back in importResultsCsv through importFailure/writeFailureResult → inputRecord.toList(), and those records went through EntityCsv.parse, so the formula escape has already been removed (- bullet). getFailedImportRowIds builds one key from each side's raw cells (lines 479 and 485). A failed row with any cell starting with =, +, -, @, tab or CR (markdown bullets and negative numbers are common) therefore never matches, and the Bulk Edit grid stops highlighting it as failed. To fix this, run the submitted cells through restoreFormula before building the key so both sides compare stored values, and add a test with a formula-like failing row.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@sonarqubecloud

sonarqubecloud Bot commented Nov 2, 2026

Copy link
Copy Markdown

@sonika-shah
sonika-shah added this pull request to the merge queue Nov 2, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-11-02T17:51:25Z)

Blocked the queue: playwright-summary

@sonika-shah
sonika-shah added this pull request to the merge queue Nov 3, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-11-03T06:56:17Z)

Blocked the queue: playwright-summary

Failed Playwright tests:

  • Pages/AIProfile/ProfileMembers.spec.ts › Should navigate from the users page to a role detail
  • Pages/AIProfile/ProfileTeam.spec.ts › Should confirm a team move in a popover, not a modal

@sonika-shah
sonika-shah added this pull request to the merge queue Nov 3, 2026
Merged via the queue into main with commit 816b235 Nov 3, 2026
88 of 89 checks passed
@sonika-shah
sonika-shah deleted the fix/csv-export-formula-injection branch November 3, 2026 12:29
harshsoni2024 added a commit that referenced this pull request Nov 3, 2026
…e-status-dos

Resolve LineageRepositoryTest conflict by keeping both the edge-pipeline authz tests and main's CSV-formula export tests (#36638, #36070). The source-file changes auto-merged: main's read-path search-lineage permission filter is complementary to this branch's write-path edge-pipeline authz.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants