refactor: extract SQL parser from regex to AST-based validation #16

Open
opened 2026-02-21 01:02:55 +00:00 by Clotho · 0 comments
Member

Summary

The SqlQueryValidator (src/Mcp/Services/SqlQueryValidator.php) currently uses regular expressions for SQL parsing and validation. This approach is fragile, hard to maintain, and can be bypassed with creative SQL syntax.

Problem

  • Complex regex patterns are difficult to audit for correctness
  • SQL dialects (MySQL, PostgreSQL, SQLite) have syntactic differences that break regex matching
  • Regex-based validation is prone to false negatives (missed injections) and false positives (blocking valid queries)
  • Adding new validation rules requires deep regex knowledge

Proposed Solution

Replace regex-based validation with an AST (Abstract Syntax Tree) parser:

  • Integrate a PHP SQL parser library (e.g. greenlion/php-sql-parser or phpmyadmin/sql-parser)
  • Walk the AST to enforce allowed node types
  • Support dialect-specific syntax natively
  • Make validation rules declarative and testable

Files

  • src/Mcp/Services/SqlQueryValidator.php
  • tests/Unit/SqlQueryValidatorTest.php (update tests)

Notes

Also noted in TODO.md under Code Quality. Estimated effort: 8-10 hours.

## Summary The `SqlQueryValidator` (src/Mcp/Services/SqlQueryValidator.php) currently uses regular expressions for SQL parsing and validation. This approach is fragile, hard to maintain, and can be bypassed with creative SQL syntax. ## Problem - Complex regex patterns are difficult to audit for correctness - SQL dialects (MySQL, PostgreSQL, SQLite) have syntactic differences that break regex matching - Regex-based validation is prone to false negatives (missed injections) and false positives (blocking valid queries) - Adding new validation rules requires deep regex knowledge ## Proposed Solution Replace regex-based validation with an AST (Abstract Syntax Tree) parser: - Integrate a PHP SQL parser library (e.g. `greenlion/php-sql-parser` or `phpmyadmin/sql-parser`) - Walk the AST to enforce allowed node types - Support dialect-specific syntax natively - Make validation rules declarative and testable ## Files - `src/Mcp/Services/SqlQueryValidator.php` - `tests/Unit/SqlQueryValidatorTest.php` (update tests) ## Notes Also noted in TODO.md under Code Quality. Estimated effort: 8-10 hours.
Clotho added the
review
refactor
discovery
labels 2026-02-21 01:02:55 +00:00
Snider added the
clotho
label 2026-02-21 01:23:16 +00:00
Charon added the
agent-ready
label 2026-02-21 01:30:15 +00:00
Sign in to join this conversation.
No description provided.