Skip to content

fix(mcp): relax column name regex, improve generate_chart validation errors and examples - #39915

Closed
aminghadersohi wants to merge 15 commits into
apache:masterfrom
aminghadersohi:amin/fix-generate-chart-column-name-validation
Closed

aminghadersohi wants to merge 15 commits into
apache:masterfrom
aminghadersohi:amin/fix-generate-chart-column-name-validation

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

Summary

Addresses validation rigidity in the generate_chart MCP tool that caused unnecessary failures when using valid but unconventionally-named columns.

Changes:

  1. Relax column name regex — Remove the pattern=r"^[a-zA-Z0-9_][a-zA-Z0-9_\s\-\.]*$" constraint from ColumnRef.name, FilterConfig.column, and BigNumberChartConfig.temporal_column. Many real-world column names (digit-prefixed like 1Q_revenue, hyphenated like order-date) were silently rejected with cryptic pydantic errors. The existing sanitize_name() / sanitize_column() validators already block XSS and SQL injection — the regex added no security value and only hurt usability.

  2. Add sanitize_temporal_column validator — BigNumberChartConfig.temporal_column now has a field_validator using sanitize_user_input with check_sql_keywords=True, matching the protection level of ColumnRef.sanitize_name.

  3. Add check_sql_keywords=True to FilterConfig.sanitize_column — ensures SQL injection patterns are blocked for filter column names.

  4. Extend docstring examples — Add generate_chart usage examples for all supported chart types: pie, big_number (with and without trendline), pivot_table, mixed_timeseries, handlebars. Update IMPORTANT section to list all 7 supported chart types.

  5. Improve validation error messages — Extract _format_single_error helper from _enhance_validation_error (reduces cyclomatic complexity) and make the fallback produce type-specific, actionable messages for string_pattern_mismatch, missing, and value_error pydantic error types. literal_error preserves the original pydantic "Input should be ..." message.

  6. Tests — New TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern classes verify: digit-prefixed and hyphenated column names now pass; script-tag XSS is blocked (nh3 strips to empty, empty-value guard rejects); event-handler injection is blocked; SQL injection is blocked; FilterConfig SQL injection is blocked.

Testing

  • Unit tests: pytest tests/unit_tests/mcp_service/chart/test_chart_schemas.py -x
  • Manual: generate_chart with a column named 1Q_revenue or order-date succeeds

…errors and examples

- Remove overly strict regex pattern from ColumnRef.name, FilterConfig.column,
  and BigNumberChartConfig.temporal_column — sanitize_name/sanitize_column
  already handle XSS/SQL injection; the pattern rejected valid column names
  like "1Q_revenue" (digit-prefixed) or "order-date" (hyphenated)
- Extend generate_chart docstring with usage examples for all supported chart
  types: pie, big_number (with/without trendline), pivot_table,
  mixed_timeseries, handlebars
- Improve _enhance_validation_error fallback in SchemaValidator to produce
  type-specific, actionable messages instead of raw pydantic error strings
  (extract _format_single_error helper to reduce cyclomatic complexity)
- Add tests verifying digit-prefixed/hyphenated column names now pass,
  and that XSS/SQL injection is still blocked by sanitize_name()
- FilterConfig.column: add check_sql_keywords=True to sanitize_column
  (Copilot review: sanitize_column was missing SQL keyword checking)
- BigNumberChartConfig.temporal_column: add sanitize_temporal_column
  field_validator using sanitize_user_input with check_sql_keywords=True
  (Copilot review: no validator after regex removal left field unprotected)
- generate_chart docstring IMPORTANT: list all chart types, not just xy/table
  (Copilot review: IMPORTANT section was misleading after adding more examples)
- Fix test_xss_attempt_blocked: nh3 strips HTML tags instead of rejecting,
  so rename to test_xss_tags_are_stripped (asserts tag is removed) and add
  test_event_handler_injection_blocked (on...= patterns ARE rejected)
- Fix _format_single_error literal_error: preserve pydantic 'Input should be'
  message instead of replacing with custom format (broke existing test
  test_non_value_error_pydantic_body_is_surfaced)
- Add test_sql_injection_in_filter_column_blocked to verify FilterConfig
  now rejects SQL injection column names
- Remove unused 'type: ignore[return-value]' from sanitize_temporal_column
  (mypy correctly infers the return type; comment was unnecessary)
- Fix test_xss_tags_are_stripped → test_script_tag_blocked: nh3 strips the
  entire script element including its content, leaving an empty string that
  the allow_empty=False guard then rejects with ValidationError
@netlify

netlify Bot commented May 6, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit a66b8d6
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/69fba671977b540008fcaa65
😎 Deploy Preview https://deploy-preview-39915--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

…ner text

nh3.clean() removes HTML tag delimiters but preserves the text content
between them, so '<script>alert(1)</script>' becomes 'alert(1)' rather
than an empty string. Update the test to assert the tag is stripped
(not that a ValidationError is raised).
@codecov

codecov Bot commented May 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 16.07143% with 47 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.91%. Comparing base (673634f) to head (644064b).
⚠️ Report is 171 commits behind head on master.

Files with missing lines Patch % Lines
...t/mcp_service/chart/validation/schema_validator.py 8.00% 23 Missing ⚠️
superset/mcp_service/chart/tool/generate_chart.py 0.00% 15 Missing ⚠️
superset/mcp_service/utils/sanitization.py 0.00% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #39915      +/-   ##
==========================================
- Coverage   64.37%   63.91%   -0.46%     
==========================================
  Files        2569     2584      +15     
  Lines      134745   136897    +2152     
  Branches    31278    31560     +282     
==========================================
+ Hits        86739    87504     +765     
- Misses      46508    47868    +1360     
- Partials     1498     1525      +27     
Flag Coverage Δ
hive 39.46% <16.07%> (-0.22%) ⬇️
mysql 59.15% <16.07%> (-0.79%) ⬇️
postgres 59.23% <16.07%> (-0.79%) ⬇️
presto 41.15% <16.07%> (-0.28%) ⬇️
python 60.67% <16.07%> (-0.89%) ⬇️
sqlite 58.87% <16.07%> (-0.77%) ⬇️
unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

nh3 behavior for '<script>alert(1)</script>' varies by version:
- some versions strip entire element (empty → ValidationError)
- others strip only tag delimiters (preserving 'alert(1)')
Accept both outcomes: no ValidationError means no <script> tag stored.

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.

Pull request overview

This PR improves the MCP generate_chart tool’s usability by loosening overly-restrictive column-name validation while keeping (and in some places strengthening) sanitization-based security checks. It also expands tool documentation examples and makes schema validation errors more actionable.

Changes:

  • Removed strict regex constraints on several column-name fields and added/strengthened sanitization validators (check_sql_keywords=True), including a new validator for BigNumberChartConfig.temporal_column.
  • Improved schema validation error formatting by extracting _format_single_error and surfacing more actionable messages/suggestions.
  • Added unit tests covering relaxed column-name acceptance plus XSS/event-handler/SQL-injection blocking; expanded generate_chart docstring examples to cover all supported chart types.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
superset/mcp_service/chart/schemas.py Removes regex patterns from column-related fields; strengthens sanitization for filter and temporal columns.
superset/mcp_service/chart/validation/schema_validator.py Refactors validation error enhancement to format per-error messages and suggestions.
superset/mcp_service/chart/tool/generate_chart.py Updates generate_chart tool docstring to list supported chart types and provide examples.
tests/unit_tests/mcp_service/chart/test_chart_schemas.py Adds tests verifying relaxed column-name handling and continued XSS/SQLi protections.

Comment thread superset/mcp_service/chart/schemas.py Resolved
…n comment

- schema_validator.py: _format_single_error string_pattern_mismatch branch
  used column-name-specific wording; generalize to apply to any pattern-
  constrained field
- schemas.py: FilterConfig.column comment referenced sanitize_name() but
  that field is validated by sanitize_column(); correct the name
…ttern

Instead of hardcoding the error message for string_pattern_mismatch errors,
extract the actual regex pattern from Pydantic's error context
(err["ctx"]["pattern"]) and include it in the message dynamically.

This gives callers the exact pattern they need to satisfy rather than a
generic hint.
@aminghadersohi
aminghadersohi marked this pull request as ready for review May 12, 2026 06:39
@dosubot dosubot Bot added the change:backend Requires changing the backend label May 12, 2026
@bito-code-review

bito-code-review Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #6e566a

Actionable Suggestions - 0
Review Details
  • Files reviewed - 4 · Commit Range: 495ed8c..ff7ace5
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/generate_chart.py
    • superset/mcp_service/chart/validation/schema_validator.py
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@fitzee fitzee 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.

Griffen Review — LGTM with nits

Note: Codex review unavailable — Griffen-only verdict below. (Known infrastructure gap.)


Context

Sources consulted: PR description, diff, sanitize_user_input implementation (superset/mcp_service/utils/sanitization.py, master), ColumnRef.sanitize_name on master (schemas.py:721).

No linked Shortcut story or GitHub issue. Reviewed on PR description alone.

Intent: Remove over-restrictive column name regex from ColumnRef.name, FilterConfig.column, and BigNumberChartConfig.temporal_column — the regex broke real-world column names (digit-prefixed, hyphenated) — and replace it with check_sql_keywords=True sanitization that provides equivalent or stronger protection. (PR description)


Door Classification

Two-way door.
Rollback complexity: Simple — restore three pattern= field arguments.
Blast radius: MCP generate_chart tool only.
Deployment reversible: Yes, unconditionally.


Security Baseline — What Actually Changed

The load-bearing question is whether the sanitizer covers what the regex covered. Before and after for each field:

Field Before After
ColumnRef.name regex + sanitize_name(check_sql_keywords=True) sanitize_name(check_sql_keywords=True) — regex dropped, no other change
FilterConfig.column regex + sanitize_column(no check_sql_keywords) sanitize_column(check_sql_keywords=True) — regex dropped, SQL check added
BigNumberChartConfig.temporal_column regex only, no sanitizer at all new sanitize_temporal_column(check_sql_keywords=True) — regex dropped, sanitizer added

ColumnRef.name is security-neutral (already had the SQL check on master). FilterConfig.column and temporal_column are strictly better: the regex was the only protection on those fields, and it was wrong — it allows SQL keywords (SELECT name FROM users is alphanumeric + spaces, passes the regex) while blocking valid column names (order-date, 1Q_revenue).

sanitize_user_input with check_sql_keywords=True enforces: nh3 HTML stripping (XSS), URL scheme blocking, event handler patterns (on\w+=), SQL DDL/DML keywords, shell metacharacters, and SQL comments. Stronger guarantees than the regex provided.

The PR description's claim that sanitization "already blocks XSS and SQL injection" is accurate for ColumnRef.name (which had it). For the other two — this PR is what adds the protection.


Medium / Low Findings

LOW — string_pattern_mismatch branch in _format_single_error is now unreachable for the three affected fields
The branch exists for other fields in the schema that still carry regex patterns, so it's not dead code. But with the three main column-name fields now pattern-free, it won't be hit through the primary user path. No correctness issue.
Mitigation: Verify other pattern-bearing fields still exist, or document the branch serves them explicitly.

NIT — test_script_tag_neutralized has a bare except: pass (test_chart_schemas.py:814)
The comment correctly explains the nh3 version variance. But pass also silently swallows ValidationErrors raised for unexpected reasons, making the test vacuously passing in failure modes.
Mitigation: In the except block, assert the specific error message — e.g. assert "cannot be empty" in str(exc_info.value) — so the test fails explicitly if the error comes from somewhere other than the empty-value guard.

NIT — literal_error and missing branches in _format_single_error not covered by tests
Pure formatting branches, no security implications. Coverage gap only.


Architectural Read

The PR makes the right structural move. A regex on a column name field was doing two jobs poorly: format enforcement (rejecting valid names) and security (allowing SQL keywords that happen to be alphanumeric). Replacing it with a purpose-built sanitizer separates those concerns correctly.

The three column-name fields now share a consistent security contract — nh3 + SQL keyword check. Previously they were inconsistent: one had it, one had a weaker version, one had only a regex.

_format_single_error is a clean extraction. The cyclomatic complexity reduction is real; the dict.fromkeys() deduplication in suggestions is the right pattern. Docstring examples are load-bearing in MCP tool descriptions — including them for all seven chart types is the right call.

Trajectory note: as chart types expand, the inline examples will grow proportionally. At some point a schema inspection tool (get_chart_schema?) will be preferable to embedding all examples in the docstring. Not a current problem.


Verdict: LGTM with nits. The security model is correct and actually stronger than what's being replaced. The nits are all in test quality and coverage — none are blockers.

@fitzee

fitzee commented May 12, 2026

Copy link
Copy Markdown
Contributor

Griffen + Codex Synthesis — LGTM with nits


Dual Review Synthesis

Griffen verdict: LGTM with nits
Codex verdict: LGTM with nits (no explicit blockers; one MEDIUM hypothesis, two LOWs)
Agreement level: Partial — both agree no blockers; Codex caught two LOWs Griffen missed

Where they agreed

  • Two-way door. Rollback: simple revert. Blast radius: MCP generate_chart only.
  • Security model is correct: sanitization replaces regex, is equivalent or stronger for all three fields.
  • _format_single_error extraction is sound; docstring examples are load-bearing and correct.
  • No CRITICAL or HIGH findings.

Where they diverged

Codex MEDIUM: relaxed punctuation acceptance (Hypothesis)
Codex flags that removing the regex now allows characters like single quotes, commas, parentheses, and brackets through schema validation, since check_sql_keywords=True doesn't block SQL-significant punctuation — only keywords and shell metacharacters. If any downstream SQL construction uses these column names without proper quoting, that's an injection vector.

Griffen's read: this is a pre-existing architectural property, not a regression introduced here. The correct invariant is quoting at SQL generation, not format restriction at schema validation. A regex that blocks ' while allowing SELECT is not a meaningful injection guard. This doesn't block merge, but Codex's suggestion to document the invariant explicitly ("column fields must resolve against dataset metadata before SQL generation") is worth doing.

Standout findings (caught by one, missed by the other)

LOW — Test suite doesn't cover the actual regression (Codex caught, Griffen missed)
The old regex ^[a-zA-Z0-9_][a-zA-Z0-9_\s\-\.]*$ already accepted 1Q_revenue (digit in [a-zA-Z0-9_]), order-date (hyphen in \-), schema.column (dot in \.), and Total Revenue (space in \s). The new tests pass under the old regex too — they don't demonstrate fixing the stated problem. The column names that actually fail the old regex would be non-ASCII (e.g., café, 客户名称), names with parentheses, slashes, single quotes, etc.
Mitigation: Add at least one test with a column name the old regex would have rejected — ideally the actual production case that motivated this PR.

LOW — check_sql_keywords=True is an undocumented validation tightening for filter/temporal columns (Codex caught, Griffen missed)
FilterConfig.column previously had no SQL keyword check (only the regex). Now it does. A column literally named update, delete, create, or alter will be rejected where it was previously accepted. Word-boundary matching (\bDELETE\b) means deleted_at or created_date are fine — the risk is exact-keyword column names, which is unusual but not impossible in some database schemas.
Mitigation: Add tests documenting this behavior explicitly, and mention it in the PR description as a known tightening.


Griffen's final call

LGTM with nits. The security model is sound and net-positive. The two LOWs above are real but not blockers — they're documentation and test coverage gaps, not correctness failures. The MEDIUM hypothesis about downstream quoting is worth tracking architecturally but doesn't change anything in this PR.

Nits to address before or after merge (none are blockers):

  1. Add a test with a column name the old regex actually rejected
  2. Document that check_sql_keywords=True is a tightening for filter/temporal columns (add to PR description or inline comment)
  3. Tighten test_script_tag_neutralized to assert the specific failure reason in the except branch

…rage

- test_script_tag_neutralized: replace bare except/pass with assertion
  that the ValidationError message contains "cannot be empty", making the
  test version-agnostic while still failing if neither expected outcome occurs
- TestFormatSingleError: cover the 'missing' and 'literal_error' branches of
  SchemaValidator._format_single_error which had no direct unit tests
…ertion

- Add docstrings to test_name_with_hyphen_accepted, test_name_with_dot_accepted,
  test_name_with_spaces_accepted, test_xy_chart_with_hyphenated_column
- In test_script_tag_neutralized success path, assert col.name is non-empty
  so a future nh3 regression that returns "" without raising cannot mask
  the validation bug
@aminghadersohi
aminghadersohi requested a review from fitzee May 13, 2026 17:27
…_user_input

nh3 can strip entire elements (e.g. <script>alert(1)</script> → ""), leaving
an empty string that bypassed the pre-strip emptiness check. Add a post-strip
guard so sanitize_user_input raises ValueError when the result is empty after
HTML sanitization, regardless of nh3 version behavior.

Also shorten test docstring to satisfy E501 (88-char line limit).
… locale tests

- sanitize_user_input: add final emptiness check after _remove_dangerous_unicode
  so zero-width-only inputs raise ValueError instead of silently returning ""
- test_sanitize_user_input_xss_entity_encoded: make version-agnostic (try/except)
  because nh3 may strip to "" (new guard raises) or preserve inner text
- add test_sanitize_user_input_zero_width_only_raises and _allow_empty_returns_none
- test_chart_schemas: add TestBigNumberTemporalColumnRelaxedPattern (3 tests)
  covering digit-prefixed, hyphenated, and SQL-injection temporal_column inputs
- test_chart_schemas: add TestLocaleColumnNamesAccepted (café_revenue, 订单日期)
Merge the None-guard and the empty-after-strip guard into a single check
via `(value or '').strip()`. Reduces McCabe complexity from 11 to 9
(ruff C901 limit is 10), with no change in observable behaviour.

@fitzee fitzee 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.

Griffen Review — fix(mcp): relax column name regex, improve generate_chart validation

Reviewed by Griffen (AI Distinguished Engineer), with Matt Fitzgerald. Reach out to Matt directly if anything needs clarifying.


Context

Sources consulted: PR description, diff, existing review comments (Copilot, CodeAnt)
Missing context: No linked Shortcut story or GitHub issue — reviewing based on PR description alone.
Intent: Remove an overly strict regex that rejected valid real-world column names (digit-prefixed, hyphenated, locale chars) from the MCP generate_chart validation layer, while tightening sanitization to compensate and improving error messages for LLM clients. (PR description)


Door Classification

Two-way door

Dimension Assessment
Rollback complexity Simple — revert restores the regex, removes the new validators, no state to unwind
Blast radius Narrow — scoped entirely to MCP generate_chart validation; no schema migrations, no data mutations, no public REST API surface affected
Deployment reversible Yes — stateless validation logic, no persistence, no protocol change
Reversibility mechanisms Not needed; inherently reversible

One caveat worth noting: if any external LLM client has been prompted or fine-tuned against the old Pydantic error message text, the improved error messages could silently break that client's error-handling logic. Still a two-way door operationally, but worth keeping in mind if you have clients with hardcoded error-response parsing.


Security

The security story holds — and is improved in one spot.

  • ColumnRef.sanitize_name() already calls sanitize_user_input with check_sql_keywords=True. Removing the regex doesn't weaken it.
  • FilterConfig.sanitize_column() previously lacked check_sql_keywords=True — this PR adds it. Good catch.
  • BigNumberChartConfig.temporal_column had no validator at all — this PR adds sanitize_temporal_column. Also good.
  • The old regex provided no security value not already covered by sanitize_user_input. Removing it is correct.

Findings

[MEDIUM] [Two-way] — test_script_tag_neutralized success branch doesn't assert content
The test's success path asserts col.name is truthy but doesn't check that the sanitized value doesn't still contain alert(1). An input where nh3 strips the tags but preserves the inner text would pass the test while storing an unsanitized payload.
Confidence: Fact (observable in test)
Mitigation: Add assert "alert" not in col.name in the try branch.

[LOW] [Two-way] — Missing XSS/event-handler test for BigNumberChartConfig.temporal_column
TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern both test XSS and event-handler injection. TestBigNumberTemporalColumnRelaxedPattern only tests SQL injection — the on...= pattern is untested for this field.
Confidence: Fact
Mitigation: Add a test_event_handler_injection_blocked to TestBigNumberTemporalColumnRelaxedPattern.

[NIT] — _format_single_error returns "" for "no suggestion"
Returning an empty string to signal "no suggestion" is implicit; tuple[str, str | None] with None would be self-documenting at the call sites. Minor — the if suggestion: guards handle it correctly as-is.


What's Good

The core design decision is sound: the regex was defense-in-depth theater that blocked legitimate inputs while providing no security value the sanitizers didn't already cover. Removing it and simultaneously adding check_sql_keywords=True to the two fields that were missing it is the right tradeoff — stricter where it matters, more permissive where it was arbitrary.

The sanitize_user_input emptiness check refactor is a genuine improvement. Inputs that reduce to empty after HTML stripping or Unicode normalization previously could slip through; the new post-strip checks close that gap correctly. The new tests (test_sanitize_user_input_zero_width_only_raises, _allow_empty_returns_none) verify the edge cases directly.

The docstring examples for all 7 chart types are the right call for an MCP tool consumed by LLM clients — concrete examples do more work than schema descriptions.


Architectural Read

This is a narrow, well-scoped cleanup. The pattern it follows — rely on explicit sanitizers rather than input-shaping regexes for security, and make the validation layer match the actual security invariant rather than a proxy for it — is the right model for an MCP validation layer that has to handle real-world user data.

No architectural concerns. The two test gaps above are the only things worth addressing before merge.


Verdict: LGTM with nits — the two test gaps are worth fixing but not worth a full review cycle. Core design is sound, merge when ready.

@fitzee

fitzee commented May 14, 2026

Copy link
Copy Markdown
Contributor

Griffen Review — fix(mcp): relax column name regex, improve generate_chart validation

Reviewed by Griffen (AI Distinguished Engineer), with Matt Fitzgerald. Reach out to Matt directly if anything needs clarifying.


Context

Sources consulted: PR description, diff, existing review comments (Copilot, CodeAnt)
Missing context: No linked Shortcut story or GitHub issue — reviewing based on PR description alone.
Intent: Remove an overly strict regex that rejected valid real-world column names (digit-prefixed, hyphenated, locale chars) from the MCP generate_chart validation layer, while tightening sanitization to compensate and improving error messages for LLM clients. (PR description)


Door Classification

Two-way door

Dimension Assessment
Rollback complexity Simple — revert restores the regex, removes the new validators, no state to unwind
Blast radius Narrow — scoped entirely to MCP generate_chart validation; no schema migrations, no data mutations, no public REST API surface affected
Deployment reversible Yes — stateless validation logic, no persistence, no protocol change
Reversibility mechanisms Not needed; inherently reversible

One caveat worth noting: if any external LLM client has been prompted or fine-tuned against the old Pydantic error message text, the improved error messages could silently break that client's error-handling logic. Still a two-way door operationally, but worth keeping in mind if you have clients with hardcoded error-response parsing.


Security

The security story holds — and is improved in one spot.

  • ColumnRef.sanitize_name() already calls sanitize_user_input with check_sql_keywords=True. Removing the regex doesn't weaken it.
  • FilterConfig.sanitize_column() previously lacked check_sql_keywords=True — this PR adds it. Good catch.
  • BigNumberChartConfig.temporal_column had no validator at all — this PR adds sanitize_temporal_column. Also good.
  • The old regex provided no security value not already covered by sanitize_user_input. Removing it is correct.

Findings

[MEDIUM] [Two-way] — test_script_tag_neutralized success branch doesn't assert content
The test's success path asserts col.name is truthy but doesn't check that the sanitized value doesn't still contain alert(1). An input where nh3 strips the tags but preserves the inner text would pass the test while storing an unsanitized payload.
Confidence: Fact (observable in test)
Mitigation: Add assert "alert" not in col.name in the try branch.

[LOW] [Two-way] — Missing XSS/event-handler test for BigNumberChartConfig.temporal_column
TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern both test XSS and event-handler injection. TestBigNumberTemporalColumnRelaxedPattern only tests SQL injection — the on...= pattern is untested for this field.
Confidence: Fact
Mitigation: Add a test_event_handler_injection_blocked to TestBigNumberTemporalColumnRelaxedPattern.

[NIT] — _format_single_error returns "" for "no suggestion"
Returning an empty string to signal "no suggestion" is implicit; tuple[str, str | None] with None would be self-documenting at the call sites. Minor — the if suggestion: guards handle it correctly as-is.


What's Good

The core design decision is sound: the regex was defense-in-depth theater that blocked legitimate inputs while providing no security value the sanitizers didn't already cover. Removing it and simultaneously adding check_sql_keywords=True to the two fields that were missing it is the right tradeoff — stricter where it matters, more permissive where it was arbitrary.

The sanitize_user_input emptiness check refactor is a genuine improvement. Inputs that reduce to empty after HTML stripping or Unicode normalization previously could slip through; the new post-strip checks close that gap correctly.

The docstring examples for all 7 chart types are the right call for an MCP tool consumed by LLM clients — concrete examples do more work than schema descriptions.


Architectural Read

Narrow, well-scoped cleanup. The pattern it follows — rely on explicit sanitizers rather than input-shaping regexes, and make the validation layer match the actual security invariant rather than a proxy for it — is the right model for an MCP validation layer handling real-world data. No architectural concerns.


Verdict: LGTM with nits — the two test gaps are worth fixing but not worth a full review cycle. Core design is sound.

…turn type, event-handler test

- test_script_tag_neutralized: add assert "alert" not in col.name in the try
  branch so payloads where nh3 strips tags but preserves inner text are also caught
- _format_single_error: change return type from tuple[str, str] to
  tuple[str, str | None]; return None instead of "" for no-suggestion branches
  (literal_error and generic fallback) — more self-documenting at call sites
- TestBigNumberTemporalColumnRelaxedPattern: add test_event_handler_injection_blocked
  to cover the on...= XSS pattern on temporal_column (mirrors existing coverage
  in TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern)
- schemas.py: document check_sql_keywords=True as a tightening vs master for
  FilterConfig.column and temporal_column, and note the word-boundary safety
  (deleted_at/created_date are fine; exact SQL keywords are rejected)

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.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

…in _format_single_error

- TestFormatSingleError.test_missing_field_message: add assert suggestion is not None
  before the `in` check — mypy correctly flags str|None as invalid right operand for `in`
- test_script_tag_neutralized: remove `assert "alert" not in col.name`; when nh3 strips
  only the tags (not the inner text), col.name == "alert(1)" which is plain text and
  therefore safe — the assertion was wrong and would fail on those nh3 versions
- _format_single_error: use `ctx = err.get("ctx") or {}` with isinstance guard instead of
  `err.get("ctx", {}).get(...)` — Pydantic can return ctx=None explicitly, which would
  cause AttributeError on the chained .get() call
@bito-code-review

bito-code-review Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ccf880

Actionable Suggestions - 0
Review Details
  • Files reviewed - 5 · Commit Range: ff7ace5..644064b
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
    • superset/mcp_service/utils/sanitization.py
    • tests/unit_tests/mcp_service/utils/test_sanitization.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/validation/schema_validator.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

aminghadersohi added a commit that referenced this pull request May 27, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request May 27, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request May 27, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request May 29, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request May 30, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 10, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 26, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 26, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 29, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 29, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
aminghadersohi added a commit that referenced this pull request Jun 30, 2026
…E001, add _reset_for_testing(), remove exec bits

schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
  in d883b62 left this field with only min/max_length guards; ColumnRef.name and
  FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
  sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
  PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
  by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
  (for import-failure path) + Exception (for third-party plugin errors) so the scope
  of each catch is explicit.

registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
  and _filter_config — gives tests a single clean-slate function instead of four
  separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
  the singleton instead of allocating a new object on every call.

file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
  files, registry.py, and initialization/__init__.py.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants