Skip to content

FIX: TransitionPQPFile: bind PQP INSERT values to prevent SQL injection - #9743

Merged
timosachsenberg merged 4 commits into
OpenMS:developfrom
aliviahossain:develop
Jul 15, 2026
Merged

timosachsenberg merged 4 commits into
OpenMS:developfrom
aliviahossain:develop

Conversation

@aliviahossain

@aliviahossain aliviahossain commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

As proposed and discussed, I audited the remaining OpenSWATH SQLite write paths and moved src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp over to parameterized inserts, closing a SQL injection in the PQP writer that the earlier fix did not cover.

I rewrote both write paths (writePQPOutput_ and convertLightTargetedExperimentToPQP) so every untrusted library string (compound, peptide, protein and gene names, SMILES, sum formula, adducts, group labels, modified sequences, annotations) is now bound as a parameter instead of concatenated into the SQL. I added a small PreparedInsert helper that prepares each statement once and does bind, step, reset per row, which mirrors the pattern OpenSwathOSWWriter already uses and keeps the existing 50,000 row batching. Numeric only mapping tables and decoy updates stay inline since they carry no user text. I also added a regression test.

Checklist

  • [ yes] Make sure that you are listed in the AUTHORS file
  • [ yes] Add relevant changes and new features to the CHANGELOG file
  • [ yes] I have commented my code, particularly in hard-to-understand areas
  • [ yes] New and existing unit tests pass locally with my changes
  • [ yes] Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

Before

Screenshot 2026-07-14 225750

insert_transition_sql << "INSERT INTO TRANSITION (...) VALUES (" << i << ",'"
<< transition.transition_name << "','" << transition.Annotation << "',...); ";
conn.executeStatement(insert_transition_sql.str()); // runs through sqlite3_exec

After

Screenshot 2026-07-14 233443

PreparedInsert insert_transition(conn.getDB(),
"INSERT INTO TRANSITION (...) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);");
...
insert_transition.bindText(2, transition.transition_name); // bound, not concatenated
insert_transition.bindText(6, transition.Annotation);
insert_transition.step(); // bind, step, reset per row, batching kept

Files changed

  • TransitionPQPFile.cpp: added the PreparedInsert helper and rewrote the TRANSITION, PRECURSOR, PROTEIN, GENE, PEPTIDE and COMPOUND inserts in both write paths to bind their string columns. Kept the 50,000 row batching.
  • TransitionPQPFile_test.cpp: regression test that round trips a library with o'brien'); DROP TABLE COMPOUND;-- in a field and checks the write succeeds, no table is dropped, and the value survives. Throws before the fix, passes after.
  • CHANGELOG: updated.

Testing

TransitionPQPFile_test and TransitionTSVFile_test pass, plus 71 of 71 TargetedFileConverter, OpenSwathDecoyGenerator and OpenSwathAssayGenerator TOPP tests (TraML to PQP to TSV round trips). Numeric columns are now bound by value, so REAL columns store full precision doubles instead of 11 digit text, which stays within FuzzyDiff tolerance.

Please review it and merge it.

Closes #9741

Summary by CodeRabbit

  • Bug Fixes / Security
    • Improved PQP export safety by switching free-text handling to prepared, parameter-bound inserts, preventing SQL injection and fixing issues with SQL-special characters.
    • Applied the same safer insertion approach across both heavy and light conversion flows, including correct handling of optional/NULL fields and consistent text round-tripping.
    • Preserved existing bulk export transaction/batching behavior for performance.
  • Tests
    • Added a regression test that injects SQL metacharacters into a text field and verifies the database schema remains unchanged and the value round-trips correctly.

@github-actions

Copy link
Copy Markdown
Contributor

@aliviahossain The following names might be missing from the AUTHORS file:

  • Alivia Hossain

  • Timo Sachsenberg

Please consider applying the following patch:

--- AUTHORS	2026-07-14 18:39:02.297639344 +0000
+++ AUTHORS.new	2026-07-14 18:39:07.597931670 +0000
@@ -14,6 +14,7 @@
  - Alexandra Scherbart
  - Alexandra Zerck
  - Alivia Hossain
+ - Alivia Hossain
  - Amanda Wein
  - Andreas Bertsch
  - Andreas Simon

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ada803be-0a93-47af-8e7f-f53d34bc18d3

📥 Commits

Reviewing files that changed from the base of the PR and between 70cd05f and 7b3e6c3.

📒 Files selected for processing (1)
  • CHANGELOG
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG

📝 Walkthrough

Walkthrough

TransitionPQPFile now uses prepared SQLite statements with bound values in both PQP-writing paths. Existing mapping batching and NULL handling remain. A regression test verifies SQL-sensitive compound strings survive writing and reading without executing injected SQL.

Changes

Parameterized PQP writes

Layer / File(s) Summary
PreparedInsert binding helper
src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp
Adds RAII statement preparation, typed binding, reset handling, and SQLite error validation.
Heavy PQP writer
src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp
Migrates transition, precursor, protein, gene, peptide, and compound inserts to bound statements while retaining batched mapping writes and NULL handling.
Light PQP writer and validation
src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp, src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp, CHANGELOG
Applies the same prepared-insert flow to light conversion and adds SQL-injection round-trip coverage and changelog documentation.

Sequence Diagram(s)

sequenceDiagram
  participant TargetedExperiment
  participant TransitionPQPFile
  participant SQLite
  TargetedExperiment->>TransitionPQPFile: provide transition-library rows
  TransitionPQPFile->>SQLite: bind and execute prepared INSERTs
  SQLite-->>TransitionPQPFile: store rows and mapping batches
  TransitionPQPFile-->>TargetedExperiment: write PQP output for round-trip reading
Loading

Poem

I’m a rabbit who binds every string,
No rogue little quote can do a thing.
Rows hop safely, batches flow,
PQP fields round-trip and glow.
SQLite sleeps beneath the spring!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: binding PQP INSERT values to fix SQL injection.
Linked Issues check ✅ Passed The PR addresses #9741 by using prepared statements in both PQP write paths and adding a regression test for injected text.
Out of Scope Changes check ✅ Passed The changes stay focused on the PQP SQL-injection fix, batching behavior, and regression coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp (1)

70-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use Exception::SqlOperationFailed for bind/step failures, matching OSWFile.cpp's convention.

PreparedInsert::fail_() throws Exception::IllegalArgument for every failure mode, including sqlite3_step execution failures and per-column bind failures. The sibling fix for the same bug class in OSWFile.cpp (checkSqliteReturnCode_/executePreparedStatement_) deliberately uses Exception::SqlOperationFailed for these runtime SQL-execution failures, reserving IllegalArgument for statement-preparation errors (malformed SQL text, as in SqliteConnector::prepareStatement). Since this PR explicitly aims to mirror OpenSwathOSWWriter's approach, aligning the exception taxonomy would keep error semantics consistent for anyone catching by exception type across the two mirrored write paths.

♻️ Suggested exception-type split
-      [[noreturn]] void fail_(const char* op)
-      {
-        throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
-          std::string(op) + " failed: " + sqlite3_errmsg(db_));
-      }
+      [[noreturn]] void fail_(const char* op)
+      {
+        throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+          std::string(op) + " failed: " + sqlite3_errmsg(db_));
+      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp` around lines 70 -
148, Update PreparedInsert::fail_() so bind and step execution failures throw
Exception::SqlOperationFailed, matching the exception taxonomy used by
OSWFile.cpp; preserve Exception::IllegalArgument for statement-preparation
failures handled by SqliteConnector::prepareStatement.
src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp (1)

208-255: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Add an equivalent injection regression test for convertLightTargetedExperimentToPQP.

This section only exercises the heavy path (convertTargetedExperimentToPQP/writePQPOutput_). The PR objectives and CHANGELOG state both write paths (writePQPOutput_ and convertLightTargetedExperimentToPQP) were parameterized to fix the same SQL-injection class; only one is regression-tested here.

Based on the PR objectives: "Both write paths ... now prepare each INSERT once and bind those columns per row ... same class of issue as #9730/#9734."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp` around lines
208 - 255, Add a parallel SQL-injection regression section covering
convertLightTargetedExperimentToPQP, using a LightTargetedExperiment with the
same quoted payload in a free-text compound field. Verify the conversion
succeeds, the COMPOUND row count is preserved, and converting the generated PQP
back retains the payload verbatim, matching the existing
convertTargetedExperimentToPQP test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp`:
- Around line 814-821: Update the PreparedInsert construction in the transition
insertion flow to replace conn.getDB() with
Internal::SqliteHelper::getNativeHandle(conn), or use the corresponding helper
overload. Apply the same change to every PreparedInsert site in this flow while
preserving the existing SQL and transaction behavior.

In `@src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp`:
- Line 224: Replace the boolean assertions in the affected test cases with the
dedicated macros: change the compounds.empty() assertion to TEST_FALSE and the
value_survived assertion to TEST_TRUE, preserving the existing expressions and
test behavior.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp`:
- Around line 70-148: Update PreparedInsert::fail_() so bind and step execution
failures throw Exception::SqlOperationFailed, matching the exception taxonomy
used by OSWFile.cpp; preserve Exception::IllegalArgument for
statement-preparation failures handled by SqliteConnector::prepareStatement.

In `@src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp`:
- Around line 208-255: Add a parallel SQL-injection regression section covering
convertLightTargetedExperimentToPQP, using a LightTargetedExperiment with the
same quoted payload in a free-text compound field. Verify the conversion
succeeds, the COMPOUND row count is preserved, and converting the generated PQP
back retains the payload verbatim, matching the existing
convertTargetedExperimentToPQP test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 896d5872-55db-47bd-8cb4-d168ed29c16e

📥 Commits

Reviewing files that changed from the base of the PR and between fc4e829 and 6df34b7.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp
  • src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp

- Route native SQLite handle through Internal::SqliteHelper::getNativeHandle
  instead of the non-existent SqliteConnector::getDB() (SQLite is now a
  private dependency, so conn.getDB() no longer compiles)
- Use Internal::SqliteHelper::prepareStatement in PreparedInsert; it is a
  free helper, not a SqliteConnector member
- Throw Exception::SqlOperationFailed for bind/step runtime failures to match
  OSWFile's convention (IllegalArgument stays for statement preparation)
- Use TEST_FALSE/TEST_TRUE for boolean assertions in the regression test
@aliviahossain

Copy link
Copy Markdown
Contributor Author

@timosachsenberg I'd appreciate if you could review this PR and merge it if found suitable. Thanks !

@timosachsenberg

Copy link
Copy Markdown
Contributor

Did you benchmark it on a large PQP file? Are there performance regressions?

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@timosachsenberg I haven't run a formal benchmark on a large library yet, mostly because I don't have a big .pqp on hand and the repo fixtures are all small. I did go through the perf side of the change though.
The read path isn't affected. The SELECT doesn't contain any untrusted data, so I didn't parameterize it, and the per-row sqlite3_step loop is the same as before.
The write path is the only place row values changed. The string columns (TRANSITION, PRECURSOR, PROTEIN, GENE, PEPTIDE, COMPOUND) now go through a single prepared statement with bind/step/reset per row instead of concatenated INSERT text, and it's still inside the same BEGIN/END TRANSACTION. A prepared statement compiles once instead of SQLite re-parsing the SQL for every row, so I'd expect writes to be about the same or slightly faster, not slower. The numeric-only mapping tables were left as batched text on purpose.

If you want real numbers I can run a before/after timing against develop. If you can point me at a representative large library that'd help, otherwise I can synthesize one with TargetedFileConverter.

@timosachsenberg

Copy link
Copy Markdown
Contributor

synthesize is fine

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@timosachsenberg Done! Benchmarked the write path on a synthesized library, as suggested.

I took one of the repo transition lists (OpenSwathAssayGenerator_output_4_roundtrip.tsv) and inflated it to about 976k transitions, then wrote it out to .pqp with TargetedFileConverter, timing the write on develop vs this branch. Same input file both times, one run:

  • Before (develop): 30.5 s
Screenshot 2026-07-15 174435 Screenshot 2026-07-15 174107
  • After (this branch): 21.9 s
Screenshot 2026-07-15 175752 Screenshot 2026-07-15 175949

No regression and slightly faster. That lines up with what I expected: the string columns now go through a single prepared statement that compiles once and does bind/step/reset per row, instead of SQLite re-parsing a freshly concatenated INSERT for every row, and it all stays inside the same BEGIN/END TRANSACTION. The read path is unchanged, so it isn't affected.

I also added a regression test that exercises the injection directly. With the parameterized writer it passes, the COMPOUND table is left intact, and the value round-trips back verbatim as data.

Please review this and you may discuss further or merge the PR if everything is clear !

@timosachsenberg

Copy link
Copy Markdown
Contributor

thats great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL injection in TransitionPQPFile PQP writer (same pattern as #9730)

2 participants