You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/10/21 15:53:41 UTC
[PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
aminghadersohi opened a new pull request, #45575:
URL: https://github.com/apache/superset/pull/45575
### SUMMARY
Follow-up to https://github.com/apache/superset/pull/45485 for two remaining diagnostic gaps:
- The sanitizer emits `string_too_long`, but `field_validation_error` replaced it with `unsafe_text`. Preserve typed sanitizer errors, including in chart-name field validators, so over-limit titles report "String exceeds the allowed maximum length" instead of "Contains disallowed content".
- `duplicate_dashboard` raised a plain `ValueError` for blank titles. Emit `empty_text` ("Text must not be empty") and keep canonical field locations for aliases.
Sibling audit:
- `generate_dashboard`, `update_dashboard`, `duplicate_dashboard`, `generate_chart`: all four `field_validation_error` call sites retain sanitizer error types; intentional plain rejection of content stripped entirely still maps to `unsafe_text`.
- `update_chart`: its existing 255-character Field constraint already reports length correctly; remove its redundant sanitizer error relabeling alongside `generate_chart`.
- Optional generate/update titles: empty-value semantics unchanged.
- `ColumnRef.name`/`label`, temporal/filter/Gantt columns and values, time ranges, comparison periods, SQL expressions, Bullet labels, and dashboard certification fields: direct typed sanitizer errors, no relabeling or untyped sanitizing rejection remains.
- `CreateThemeRequest.reject_blank_theme_name`: plain blank-name validation, but not a sanitizing validator; unchanged and outside these title-sanitization paths.
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not applicable; MCP error text only. Rejected values are never echoed in wire diagnostics.
### TESTING INSTRUCTIONS
Run with the repository and `superset-core/src` on `PYTHONPATH`:
```bash
pytest -q tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py \
tests/unit_tests/mcp_service/test_validation_contract.py \
tests/unit_tests/mcp_service/utils/test_sanitization*.py \
tests/unit_tests/mcp_service/utils/test_schema_utils.py \
tests/unit_tests/mcp_service/utils/test_error_sanitization.py \
-m 'not manual and not llm_compliance'
```
New FastMCP server/client wire regressions cover limit+1 and 600-character titles, canonical/title/name inputs, and empty/whitespace-only duplicate titles. Against unmodified master: 30 failed, 6 passed (145 deselected). After the change: all 36 new wire cases pass within 777 passing tests across the command above. `pre-commit run` on the five changed files passes, including mypy. Real-LLM checks were not run (OpenRouter disabled).
### ADDITIONAL INFORMATION
- No UI, database migration, or feature flag changes.
- Separate follow-up requested for these gaps; the related chart-filter work in https://github.com/apache/superset/pull/45486 is unchanged.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366992203
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
Correction to my reply above: the sibling entries `superset/mcp_service/theme/schemas.py:138` and `superset/mcp_service/theme/schemas.py:155` — not affected are wrong. This PR adds `max_length=250` to `CreateThemeRequest.theme_name`, and that cap runs before `reject_blank_theme_name`, so `create_theme` with `theme_name=" " * 300` fails with `string_too_long` at `theme_name` at 705c6f0bc395800d6b5fee03d5bef0a9830b1852. Before this PR it got the blank-name error, and the updated docs say blank `create_theme` names report "Text must not be empty". The same doc sentence also does not hold for whitespace-only `metric_name` (`create_dataset_metric` / `update_dataset_metric`, cap 255) or `update_dataset` `table_name` (cap 250) over their caps; those report `string_too_long` (that ordering predates this PR). Not fixed yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366959191
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
The remaining namespace byte-input gap is fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852. `CreateDatasetRequest.schema_` (including the `schema` alias) and `catalog` decode UTF-8 bytes/bytearray before trimming, blank-to-None normalization, and the 250-character cap. Invalid UTF-8 chart/dashboard titles retain a field-located `string_unicode` error. The audit also found and corrected the same string-only bypass in `GetChartInfoRequest.permalink_key` URL extraction.
Regression tests in tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py, run against untouched source at 746c57391cecb0fba4771a678914bfa1131efd73 and this commit:
- test_byte_dataset_namespace_normalizes_before_length: 24 fail before / pass after; covers padded values, short/251-character blanks, exact-limit names, both byte types, both namespace fields, and the schema alias. It also checks the exact properties passed to dataset creation and omission of blank namespaces.
- test_invalid_utf8_title_error_is_field_located: 48 fail before / pass after across all title-writing models and aliases, including saved/unsaved chart generation.
- test_byte_permalink_url_extracts_key and test_byte_permalink_rejects_other_url: 4 fail before / pass after, covering the success and rejection paths.
- test_dataset_namespace_rejects_malformed_values: 21 passing controls before and after, preserving type rejection, field locations, and the real over-limit cap.
Final regression comparison: 76 failed / 21 passed before; 97 passed after. Full touched files: 1,633 passed. Changed-file pre-commit and explicit mypy passed; the branch's three frontend Jest suites passed (32 tests). Real-LLM checks excluded (OpenRouter disabled).
I searched every `@field_validator` in `superset/mcp_service/**/schemas.py` with an AST inventory (88 validators), plus `rg -n 'validator|isinstance.*str|decode\(' superset/mcp_service -g schemas.py` and callers of `CreateDatasetRequest`, `GetChartInfoRequest`, and `field_validation_error`. Full sibling audit follows; earlier already-decoding paths are distinguished from the namespace/title/permalink changes in this commit.
Siblings checked:
- superset/mcp_service/catalog/schemas.py:79 — not affected: GetCatalogRequest._normalize_search: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/catalog/schemas.py:87 — not affected: GetCatalogRequest._normalize_cursor: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:452 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/chart/schemas.py:484 — not affected: GetChartInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/chart/schemas.py:879 — not affected: BaseChartConfig.sanitize_temporal_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1005 — not affected: ColumnRef.sanitize_name: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1017 — not affected: ColumnRef.sanitize_label: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1027 — not affected: ColumnRef.sanitize_sql: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1140 — not affected: FilterConfig.sanitize_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1152 — not affected: FilterConfig.sanitize_value: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1223 — not affected: GanttSortByConfig.sanitize_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1547 — not affected: GaugeChartConfig.validate_gauge_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1712 — not affected: TreemapChartUpdateConfig.validate_treemap_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:2335 — not affected: SunburstLegacySavedFields.validate_legacy_limit: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:2777 — not affected: SunburstChartConfig.sanitize_time_range: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:3173 — not affected: InteractivePivotChartConfig.sanitize_comparison_period: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:3340 — not affected: MixedTimeseriesChartConfig.wrap_single_group_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4080 — not affected: XYChartConfig.coerce_sort_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4105 — not affected: XYChartConfig.coerce_series_ranking_metric: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4117 — not affected: XYChartConfig.validate_series_ranking_metric: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4129 — not affected: XYChartConfig.wrap_single_group_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4134 — not affected: XYChartConfig.coerce_x_column_name: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4140 — not affected: XYChartConfig.coerce_y_column_names: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4156 — not affected: XYChartConfig.coerce_legend_flag: boolean-to-model shorthand, not a string-only normalizer.
- superset/mcp_service/chart/schemas.py:4611 — not affected: BulletChartConfig.tokenize_native_numeric_lists: native list shorthand; bare bytes are rejected by the list field, and label list elements sanitize after string coercion.
- superset/mcp_service/chart/schemas.py:4623 — not affected: BulletChartConfig.tokenize_native_label_lists: native list shorthand; bare bytes are rejected by the list field, and label list elements sanitize after string coercion.
- superset/mcp_service/chart/schemas.py:4633 — not affected: BulletChartConfig.reject_non_finite_values: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4640 — not affected: BulletChartConfig.validate_presentation_labels: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4660 — not affected: BulletChartConfig.sanitize_time_range: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:5625 — not affected: GanttChartConfig.coerce_single_column: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5631 — not affected: GanttChartConfig.coerce_tooltip_columns: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5638 — not affected: GanttChartConfig.parse_native_order_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5674 — not affected: GanttChartConfig.validate_gantt_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:5679 — not affected: GanttChartConfig.validate_time_bounds: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:5805 — not affected: GeographicChartConfig.validate_geographic_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:6426 — not affected: ChartNameMixin.normalize_blank_chart_name: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:7297 — not affected: RestoreChartRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/chart/schemas.py:7339 — not affected: DeleteChartRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:371 — not affected: GetDashboardInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dashboard/schemas.py:913 — not affected: GenerateDashboardRequest.normalize_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:1084 — not affected: UpdateDashboardRequest.normalize_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:1094 — not affected: UpdateDashboardRequest.normalize_slug: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1195 — not affected: ManageDashboardOwnersRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1204 — not affected: ManageDashboardOwnersRequest.reject_bool_owner_ids: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1294 — not affected: ManageDashboardRolesRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1303 — not affected: ManageDashboardRolesRequest.reject_bool_role_ids: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1394 — not affected: ManageDashboardCertificationRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1403 — not affected: ManageDashboardCertificationRequest.sanitize_certified_by: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1427 — not affected: ManageDashboardCertificationRequest.sanitize_certification_details: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1581 — not affected: DuplicateDashboardRequest.reject_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2315 — not affected: DeleteDashboardRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2380 — not affected: BaseNewFilterSpec.reject_bool_dataset_id: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2448 — not affected: FilterTimeSpec._validate_default_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2582 — not affected: NativeFilterUpdateSpec._validate_default_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2596 — not affected: NativeFilterUpdateSpec.reject_bool_dataset_id: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2773 — not affected: HeaderComponentSpec.sanitize_text: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2834 — not affected: DashboardComponentUpdateSpec.sanitize_text: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3005 — not affected: ApplyFilterValueSpec._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3011 — not affected: ApplyFilterValueSpec._validate_range_order: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3483 — not affected: RestoreDashboardRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:3570 — not affected: GetDashboardDataRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:344 — not affected: ListDatasetsRequest.parse_filters: passthrough with no string-only normalization.
- superset/mcp_service/dataset/schemas.py:349 — not affected: ListDatasetsRequest.parse_select_columns: passthrough with no string-only normalization.
- superset/mcp_service/dataset/schemas.py:439 — not affected: GetDatasetInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dataset/schemas.py:449 — not affected: GetDatasetInfoRequest._parse_column_fields: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dataset/schemas.py:474 — not affected: CreateDatasetMetric.expression_must_aggregate: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:485 — not affected: CreateDatasetMetric.d3format_must_be_valid: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:556 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dataset/schemas.py:571 — not affected: CreateDatasetRequest._strip_table_name: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dataset/schemas.py:627 — not affected: CreateVirtualDatasetRequest.sql_must_not_be_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:634 — not affected: CreateVirtualDatasetRequest.dataset_name_must_not_be_empty: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dataset/schemas.py:749 — not affected: DatasetMetricProperties.d3format_must_be_valid: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:912 — not affected: DeleteDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:973 — not affected: RestoreDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1056 — not affected: UpdateDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1065 — not affected: UpdateDatasetRequest.reject_bool_cache_timeout: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1257 — not affected: QueryDatasetRequest._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/semantic_layer/schemas.py:273 — not affected: GetTableRequest.normalize_time_grain: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/semantic_layer/schemas.py:309 — not affected: GetTableRequest._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:108 — not affected: ExecuteSqlRequest.sql_not_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:123 — not affected: ColumnInfo.coerce_is_nullable: response metadata coercion, not a request normalization path.
- superset/mcp_service/sql_lab/schemas.py:263 — not affected: SaveSqlQueryRequest.sql_not_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:270 — not affected: SaveSqlQueryRequest.label_not_empty: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/sql_lab/schemas.py:335 — not affected: OpenSqlLabRequest.title_strip_or_none: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/system/schemas.py:219 — not affected: FindUsersRequest._reject_blank_query: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/system/schemas.py:230 — not affected: FindUsersRequest._reject_email_shaped_query: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/theme/schemas.py:155 — not affected: CreateThemeRequest.reject_blank_theme_name: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/user/schemas.py:104 — not affected: UserInfo._extract_role_names: response metadata coercion, not a request normalization path.
- superset/mcp_service/chart/schemas.py:6373 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:859 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:1031 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:1527 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/utils/schema_utils.py:41 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dataset/schemas.py:580 — not affected: CreateVirtualDatasetRequest schema/catalog do not promise trim/blank normalization for string inputs either.
- superset/mcp_service/dataset/schemas.py:701 — not affected: DatasetMetricProperties and its create/update subclasses validate literal metric names after coercion; they deliberately retain whitespace.
- superset/mcp_service/dataset/schemas.py:1012 — not affected: UpdateDatasetRequest validates its literal table_name after coercion; it deliberately retains whitespace.
- superset/mcp_service/dataset/schemas.py:881 — not affected: slice_name is response metadata, not a title-writing request.
- superset/mcp_service/chart/schemas.py:6469 — not affected: GenerateExploreLinkRequest has no chart-name field.
- superset/mcp_service/chart/schemas.py:6576 — not affected: UpdateChartPreviewRequest has no chart-name field.
- superset/mcp_service/dataset/tool/create_dataset.py:97 — not affected: _build_dataset_properties consumes the normalized typed request; the new namespace regression also asserts the exact persisted properties and omitted blank keys.
- superset/mcp_service/chart/tool/get_chart_info.py:550 — not affected: the cache loader consumes the validated permalink key; it has no separate raw-input decoder.
- superset/mcp_service/chart/tool/generate_chart.py:255 — not affected: revalidation carries the already-sanitized chart_name; no second raw-byte entry point.
- superset/mcp_service/chart/tool/update_chart.py — not affected: consumes UpdateChartRequest, which inherits the shared chart-name guard.
- superset/mcp_service/dashboard/tool/generate_dashboard.py — not affected: consumes GenerateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/dashboard/tool/update_dashboard.py — not affected: consumes UpdateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/dashboard/tool/duplicate_dashboard.py — not affected: consumes DuplicateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/utils/validation.py:251 — not affected: formats only schema-backed locations and static reasons, without msg, ctx, or input.
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,789 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_escaped_title_still_fits_model_column(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Conservative bracket escaping cannot bypass a persisted title's length cap."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2) + "<ſ"
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("whitespace", ["\t", "\n", "\r", "\v", "\f", "\x85"])
+@pytest.mark.parametrize(
+ "control",
+ ["!channel", "@U123", "#C123|general", "https://example.invalid|Open dashboard"],
+)
+def test_title_control_whitespace_cannot_form_slack_markup(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ whitespace: str,
+ control: str,
+) -> None:
+ """Report title normalization must not join brackets into Slack controls."""
+ from superset.utils.file import sanitize_title
+
+ value = f"Q3 <{whitespace}{control}>"
+ request = model.model_validate({**payload, field: value})
+ stored = getattr(request, field)
+ assert "<" not in sanitize_title(stored)
+ assert getattr(model.model_validate(request.model_dump()), field) == stored
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("alias_index", range(4))
+@pytest.mark.parametrize("length_delta", [-5, 0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_markup_title_length_uses_sanitized_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ alias_index: int,
+ length_delta: int,
+ padding: str,
+) -> None:
+ """Markup is not part of the persisted title's character budget."""
+ aliases = (
+ ("chart_name", "name", "title", "slice_name")
+ if field == "chart_name"
+ else ("dashboard_title", "title", "name", "dashboard_title")
+ )
+ limit = 250 if field == "chart_name" else 500
+ text = "x" * (limit + length_delta)
+ value = "<b>" + padding + text + padding + "</b>"
+ if length_delta > 0:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, aliases[alias_index]: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate({**payload, aliases[alias_index]: value})
+ assert getattr(request, field) == text
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [case for case in _SIBLING_SANITIZATION_CASES if case[2] != "value"],
+)
+@pytest.mark.parametrize("extra", [0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_sibling_sanitized_length_budget(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ extra: int,
+ padding: str,
+) -> None:
+ """All callers of the shared text sanitizer enforce the final text cap."""
+ limits = {
+ "certified_by": 500,
+ "certification_details": 5000,
+ "temporal_column": 255,
+ "name": 255,
+ "label": 500,
+ "column": 255,
+ "time_range": 1000,
+ "comparison_period": 100,
+ "range_labels": 200,
+ "marker_labels": 200,
+ "marker_line_labels": 200,
+ }
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ text = "x" * (limits[field] + extra)
+ value = "<b>" + padding + text + padding + "</b>"
+ if extra:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert getattr(request, field) == (
+ [text] if field.endswith("_labels") else text
+ )
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ case
+ for case in _SIBLING_SANITIZATION_CASES
+ if case[2] != "value" and not case[2].endswith("_labels")
+ ],
+)
+@pytest.mark.parametrize("value", [b"<b>Safe</b>", bytearray(b"<b>Safe</b>")])
Review Comment:
The remaining namespace byte-input gap is fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852. `CreateDatasetRequest.schema_` (including the `schema` alias) and `catalog` decode UTF-8 bytes/bytearray before trimming, blank-to-None normalization, and the 250-character cap. Invalid UTF-8 chart/dashboard titles retain a field-located `string_unicode` error. The audit also found and corrected the same string-only bypass in `GetChartInfoRequest.permalink_key` URL extraction.
Regression tests in tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py, run against untouched source at 746c57391cecb0fba4771a678914bfa1131efd73 and this commit:
- test_byte_dataset_namespace_normalizes_before_length: 24 fail before / pass after; covers padded values, short/251-character blanks, exact-limit names, both byte types, both namespace fields, and the schema alias. It also checks the exact properties passed to dataset creation and omission of blank namespaces.
- test_invalid_utf8_title_error_is_field_located: 48 fail before / pass after across all title-writing models and aliases, including saved/unsaved chart generation.
- test_byte_permalink_url_extracts_key and test_byte_permalink_rejects_other_url: 4 fail before / pass after, covering the success and rejection paths.
- test_dataset_namespace_rejects_malformed_values: 21 passing controls before and after, preserving type rejection, field locations, and the real over-limit cap.
Final regression comparison: 76 failed / 21 passed before; 97 passed after. Full touched files: 1,633 passed. Changed-file pre-commit and explicit mypy passed; the branch's three frontend Jest suites passed (32 tests). Real-LLM checks excluded (OpenRouter disabled).
I searched every `@field_validator` in `superset/mcp_service/**/schemas.py` with an AST inventory (88 validators), plus `rg -n 'validator|isinstance.*str|decode\(' superset/mcp_service -g schemas.py` and callers of `CreateDatasetRequest`, `GetChartInfoRequest`, and `field_validation_error`. Full sibling audit follows; earlier already-decoding paths are distinguished from the namespace/title/permalink changes in this commit.
Siblings checked:
- superset/mcp_service/catalog/schemas.py:79 — not affected: GetCatalogRequest._normalize_search: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/catalog/schemas.py:87 — not affected: GetCatalogRequest._normalize_cursor: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:452 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/chart/schemas.py:484 — not affected: GetChartInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/chart/schemas.py:879 — not affected: BaseChartConfig.sanitize_temporal_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1005 — not affected: ColumnRef.sanitize_name: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1017 — not affected: ColumnRef.sanitize_label: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1027 — not affected: ColumnRef.sanitize_sql: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1140 — not affected: FilterConfig.sanitize_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1152 — not affected: FilterConfig.sanitize_value: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1223 — not affected: GanttSortByConfig.sanitize_column: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:1547 — not affected: GaugeChartConfig.validate_gauge_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:1712 — not affected: TreemapChartUpdateConfig.validate_treemap_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:2335 — not affected: SunburstLegacySavedFields.validate_legacy_limit: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:2777 — not affected: SunburstChartConfig.sanitize_time_range: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:3173 — not affected: InteractivePivotChartConfig.sanitize_comparison_period: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:3340 — not affected: MixedTimeseriesChartConfig.wrap_single_group_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4080 — not affected: XYChartConfig.coerce_sort_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4105 — not affected: XYChartConfig.coerce_series_ranking_metric: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4117 — not affected: XYChartConfig.validate_series_ranking_metric: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4129 — not affected: XYChartConfig.wrap_single_group_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4134 — not affected: XYChartConfig.coerce_x_column_name: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4140 — not affected: XYChartConfig.coerce_y_column_names: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:4156 — not affected: XYChartConfig.coerce_legend_flag: boolean-to-model shorthand, not a string-only normalizer.
- superset/mcp_service/chart/schemas.py:4611 — not affected: BulletChartConfig.tokenize_native_numeric_lists: native list shorthand; bare bytes are rejected by the list field, and label list elements sanitize after string coercion.
- superset/mcp_service/chart/schemas.py:4623 — not affected: BulletChartConfig.tokenize_native_label_lists: native list shorthand; bare bytes are rejected by the list field, and label list elements sanitize after string coercion.
- superset/mcp_service/chart/schemas.py:4633 — not affected: BulletChartConfig.reject_non_finite_values: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4640 — not affected: BulletChartConfig.validate_presentation_labels: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:4660 — not affected: BulletChartConfig.sanitize_time_range: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/chart/schemas.py:5625 — not affected: GanttChartConfig.coerce_single_column: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5631 — not affected: GanttChartConfig.coerce_tooltip_columns: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5638 — not affected: GanttChartConfig.parse_native_order_by: list/model shorthand; byte input cannot bypass into a stored string because the target list/model validation rejects it.
- superset/mcp_service/chart/schemas.py:5674 — not affected: GanttChartConfig.validate_gantt_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:5679 — not affected: GanttChartConfig.validate_time_bounds: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:5805 — not affected: GeographicChartConfig.validate_geographic_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:6426 — not affected: ChartNameMixin.normalize_blank_chart_name: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/chart/schemas.py:7297 — not affected: RestoreChartRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/chart/schemas.py:7339 — not affected: DeleteChartRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:371 — not affected: GetDashboardInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dashboard/schemas.py:913 — not affected: GenerateDashboardRequest.normalize_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:1084 — not affected: UpdateDashboardRequest.normalize_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:1094 — not affected: UpdateDashboardRequest.normalize_slug: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1195 — not affected: ManageDashboardOwnersRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1204 — not affected: ManageDashboardOwnersRequest.reject_bool_owner_ids: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1294 — not affected: ManageDashboardRolesRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1303 — not affected: ManageDashboardRolesRequest.reject_bool_role_ids: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1394 — not affected: ManageDashboardCertificationRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:1403 — not affected: ManageDashboardCertificationRequest.sanitize_certified_by: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1427 — not affected: ManageDashboardCertificationRequest.sanitize_certification_details: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dashboard/schemas.py:1581 — not affected: DuplicateDashboardRequest.reject_blank_dashboard_title: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2315 — not affected: DeleteDashboardRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2380 — not affected: BaseNewFilterSpec.reject_bool_dataset_id: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2448 — not affected: FilterTimeSpec._validate_default_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2582 — not affected: NativeFilterUpdateSpec._validate_default_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2596 — not affected: NativeFilterUpdateSpec.reject_bool_dataset_id: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:2773 — not affected: HeaderComponentSpec.sanitize_text: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:2834 — not affected: DashboardComponentUpdateSpec.sanitize_text: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3005 — not affected: ApplyFilterValueSpec._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3011 — not affected: ApplyFilterValueSpec._validate_range_order: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dashboard/schemas.py:3483 — not affected: RestoreDashboardRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dashboard/schemas.py:3570 — not affected: GetDashboardDataRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:344 — not affected: ListDatasetsRequest.parse_filters: passthrough with no string-only normalization.
- superset/mcp_service/dataset/schemas.py:349 — not affected: ListDatasetsRequest.parse_select_columns: passthrough with no string-only normalization.
- superset/mcp_service/dataset/schemas.py:439 — not affected: GetDatasetInfoRequest._parse_select_columns: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dataset/schemas.py:449 — not affected: GetDatasetInfoRequest._parse_column_fields: list parser; bare bytes are rejected by the list field rather than persisted as unnormalized text.
- superset/mcp_service/dataset/schemas.py:474 — not affected: CreateDatasetMetric.expression_must_aggregate: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:485 — not affected: CreateDatasetMetric.d3format_must_be_valid: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:556 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dataset/schemas.py:571 — not affected: CreateDatasetRequest._strip_table_name: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dataset/schemas.py:627 — not affected: CreateVirtualDatasetRequest.sql_must_not_be_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:634 — not affected: CreateVirtualDatasetRequest.dataset_name_must_not_be_empty: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/dataset/schemas.py:749 — not affected: DatasetMetricProperties.d3format_must_be_valid: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/dataset/schemas.py:912 — not affected: DeleteDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:973 — not affected: RestoreDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1056 — not affected: UpdateDatasetRequest.reject_bool_identifier: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1065 — not affected: UpdateDatasetRequest.reject_bool_cache_timeout: boolean-ID/numeric guard, not a string-only text normalizer.
- superset/mcp_service/dataset/schemas.py:1257 — not affected: QueryDatasetRequest._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/semantic_layer/schemas.py:273 — not affected: GetTableRequest.normalize_time_grain: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/semantic_layer/schemas.py:309 — not affected: GetTableRequest._validate_time_range: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:108 — not affected: ExecuteSqlRequest.sql_not_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:123 — not affected: ColumnInfo.coerce_is_nullable: response metadata coercion, not a request normalization path.
- superset/mcp_service/sql_lab/schemas.py:263 — not affected: SaveSqlQueryRequest.sql_not_empty: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/sql_lab/schemas.py:270 — not affected: SaveSqlQueryRequest.label_not_empty: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/sql_lab/schemas.py:335 — not affected: OpenSqlLabRequest.title_strip_or_none: already decodes bytes/bytearray before text normalization; field-validator errors already carry a field location.
- superset/mcp_service/system/schemas.py:219 — not affected: FindUsersRequest._reject_blank_query: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/system/schemas.py:230 — not affected: FindUsersRequest._reject_email_shaped_query: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/theme/schemas.py:155 — not affected: CreateThemeRequest.reject_blank_theme_name: runs after Pydantic validates/coerces its declared field, so bytes cannot skip the validator.
- superset/mcp_service/user/schemas.py:104 — not affected: UserInfo._extract_role_names: response metadata coercion, not a request normalization path.
- superset/mcp_service/chart/schemas.py:6373 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:859 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:1031 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dashboard/schemas.py:1527 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/utils/schema_utils.py:41 — fixed in 705c6f0bc395800d6b5fee03d5bef0a9830b1852
- superset/mcp_service/dataset/schemas.py:580 — not affected: CreateVirtualDatasetRequest schema/catalog do not promise trim/blank normalization for string inputs either.
- superset/mcp_service/dataset/schemas.py:701 — not affected: DatasetMetricProperties and its create/update subclasses validate literal metric names after coercion; they deliberately retain whitespace.
- superset/mcp_service/dataset/schemas.py:1012 — not affected: UpdateDatasetRequest validates its literal table_name after coercion; it deliberately retains whitespace.
- superset/mcp_service/dataset/schemas.py:881 — not affected: slice_name is response metadata, not a title-writing request.
- superset/mcp_service/chart/schemas.py:6469 — not affected: GenerateExploreLinkRequest has no chart-name field.
- superset/mcp_service/chart/schemas.py:6576 — not affected: UpdateChartPreviewRequest has no chart-name field.
- superset/mcp_service/dataset/tool/create_dataset.py:97 — not affected: _build_dataset_properties consumes the normalized typed request; the new namespace regression also asserts the exact persisted properties and omitted blank keys.
- superset/mcp_service/chart/tool/get_chart_info.py:550 — not affected: the cache loader consumes the validated permalink key; it has no separate raw-input decoder.
- superset/mcp_service/chart/tool/generate_chart.py:255 — not affected: revalidation carries the already-sanitized chart_name; no second raw-byte entry point.
- superset/mcp_service/chart/tool/update_chart.py — not affected: consumes UpdateChartRequest, which inherits the shared chart-name guard.
- superset/mcp_service/dashboard/tool/generate_dashboard.py — not affected: consumes GenerateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/dashboard/tool/update_dashboard.py — not affected: consumes UpdateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/dashboard/tool/duplicate_dashboard.py — not affected: consumes DuplicateDashboardRequest; shared schema owns byte decoding.
- superset/mcp_service/utils/validation.py:251 — not affected: formats only schema-backed locations and static reasons, without msg, ctx, or input.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4342213504
##########
tests/unit_tests/mcp_service/utils/test_sanitization.py:
##########
@@ -903,3 +903,69 @@ def test_data_label_followed_by_control_whitespace_is_preserved(
"""Whitespace after a comma-free data: label may be a tab or line break."""
value = f"Substitute data:{separator}Jira support tickets"
assert sanitize(value) == value.replace("\r\n", "\n")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "5 < 10",
+ "A < B",
+ "A <",
+ "A <> B",
+ ],
+)
+def test_strip_html_tags_preserves_non_tag_less_than(value: str) -> None:
+ """Preserve display text without decoding tag-opening brackets."""
+ assert _strip_html_tags(value) == value.replace(">", ">")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "<</b>script>alert(1)",
+ "<​script>alert(1)",
+ "<</b>img src=x onerror=alert(1)",
+ ],
+)
+def test_strip_html_tags_does_not_reconstruct_tag_openers(value: str) -> None:
+ """Removed tags or invisible characters must not reveal raw markup."""
+ result = _strip_html_tags(value)
+ assert "<script" not in result
+ assert "<img" not in result
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "<<b></b>script>alert(1)",
+ "<​script>alert(1)",
+ "&lt;</script>click= <b>📈",
+ "<<</b>x",
+ ],
+)
+def test_sanitize_user_input_rejects_reconstructed_tag_text(value: str) -> None:
+ """Tag-shaped text left after stripping is rejected, never stored."""
+ with pytest.raises(ValueError, match="malicious HTML"):
+ sanitize_user_input(value, "Title")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "A <> B",
+ "a << b",
+ "Weekly <img src=x>KPIs",
+ "Q3 <b>revenue</b> & costs",
+ "<3 charts",
Review Comment:
The resubmission-stability cases don't cover entities rebuilt by tag removal. With the head sanitizer, `Weekly &am<b></b>p;lt;b&gt;KPIs` is stored as `Weekly &lt;b>KPIs`, and sending that stored title back sanitizes it to `Weekly KPIs`, so a round-trip silently changes the title. Is that intended, or should this input be added here and the single pass made stable for it?
##########
docs/admin_docs/configuration/mcp-server.mdx:
##########
@@ -2424,3 +2424,18 @@ Context names are returned verbatim per the Tool Result Value Contract.
"Did you mean" column candidates also preserve dataset spelling, including
quotes and ampersands, with a 200-character bound per candidate. Use
`get_dataset_info` for the complete schema.
+
+### Title validation errors
+
+Rejected MCP titles report a field-specific reason without echoing the input.
+Titles exceeding 500 characters for dashboards or 250 characters for charts
+report "String exceeds the allowed maximum length". `duplicate_dashboard`
+requires a non-blank title and reports "Text must not be empty" when no text
Review Comment:
A `duplicate_dashboard` title such as `<script>alert(1)</script>` is stripped to nothing and rejected through the plain `ValueError` path, so clients get "Contains disallowed content" (`unsafe_text`), not "Text must not be empty". Only originally blank/whitespace titles reach `empty_text`, so a client following this paragraph would misclassify the stripped-only case. Should this sentence say "blank or whitespace-only" and name the stripped-only case separately?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4343902099
##########
tests/unit_tests/mcp_service/utils/test_sanitization.py:
##########
@@ -903,3 +903,69 @@ def test_data_label_followed_by_control_whitespace_is_preserved(
"""Whitespace after a comma-free data: label may be a tab or line break."""
value = f"Substitute data:{separator}Jira support tickets"
assert sanitize(value) == value.replace("\r\n", "\n")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "5 < 10",
+ "A < B",
+ "A <",
+ "A <> B",
+ ],
+)
+def test_strip_html_tags_preserves_non_tag_less_than(value: str) -> None:
+ """Preserve display text without decoding tag-opening brackets."""
+ assert _strip_html_tags(value) == value.replace(">", ">")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "<</b>script>alert(1)",
+ "<​script>alert(1)",
+ "<</b>img src=x onerror=alert(1)",
+ ],
+)
+def test_strip_html_tags_does_not_reconstruct_tag_openers(value: str) -> None:
+ """Removed tags or invisible characters must not reveal raw markup."""
+ result = _strip_html_tags(value)
+ assert "<script" not in result
+ assert "<img" not in result
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "<<b></b>script>alert(1)",
+ "<​script>alert(1)",
+ "&lt;</script>click= <b>📈",
+ "<<</b>x",
+ ],
+)
+def test_sanitize_user_input_rejects_reconstructed_tag_text(value: str) -> None:
+ """Tag-shaped text left after stripping is rejected, never stored."""
+ with pytest.raises(ValueError, match="malicious HTML"):
+ sanitize_user_input(value, "Title")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "A <> B",
+ "a << b",
+ "Weekly <img src=x>KPIs",
+ "Q3 <b>revenue</b> & costs",
+ "<3 charts",
Review Comment:
Fixed in 445b90b267. I extended the existing rejection policy: text that rebuilds entities and would change on a second HTML-stripping pass is rejected as unsafe_text rather than stored. `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_reject_entities_reconstructed_by_removal` includes the exact example, hex or named entity fragments, and Unicode removal across the text sanitizer, warning wrapper, and filter sanitizer. The new tests reproduced 35 failures on the previous head across unit and wire cases; the updated sanitizer/wire modules pass 765 tests. The shared title and sibling-field wire tests also cover the rebuilt-entity input.
Siblings checked:
- superset/mcp_service/utils/sanitization.py:326 — fixed in 445b90b267
- superset/mcp_service/utils/sanitization.py:387 — fixed in 445b90b267
- superset/mcp_service/utils/sanitization.py:237 — fixed in 445b90b267
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 445b90b267
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 445b90b267
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 445b90b267
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 445b90b267
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:879 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:1003 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:1011 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:1132 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:1143 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:1211 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:2761 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:3155 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:4628 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:4637 — fixed in 445b90b267
- superset/mcp_service/chart/schemas.py:6369 — fixed in 445b90b267
- superset/mcp_service/utils/sanitization.py:443 — not affected: SQL expressions reject HTML constructs instead of stripping tags; they do not use the changed HTML-removal path.
- superset/mcp_service/utils/error_builder.py:54 — not affected: independent error-context sanitizer, not a persisted input or a caller of _strip_html_tags.
##########
docs/admin_docs/configuration/mcp-server.mdx:
##########
@@ -2424,3 +2424,18 @@ Context names are returned verbatim per the Tool Result Value Contract.
"Did you mean" column candidates also preserve dataset spelling, including
quotes and ampersands, with a 200-character bound per candidate. Use
`get_dataset_info` for the complete schema.
+
+### Title validation errors
+
+Rejected MCP titles report a field-specific reason without echoing the input.
+Titles exceeding 500 characters for dashboards or 250 characters for charts
+report "String exceeds the allowed maximum length". `duplicate_dashboard`
+requires a non-blank title and reports "Text must not be empty" when no text
Review Comment:
Documentation corrected in 445b90b267: blank/whitespace-only input reports empty_text, while stripped-only script content reports unsafe_text. `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_duplicate_dashboard_removed_or_unstable_title_wire_reason` pins the full wire message for all three aliases. The script-only cases preserve existing behavior (they also pass before this documentation correction); its rebuilt-entity cases fail on the previous head and pass with this commit.
Siblings checked:
- docs/admin_docs/configuration/mcp-server.mdx:2433 — fixed in 445b90b267
- docs/developer_docs/extensions/mcp.md:603 — not affected: the blank-name paragraph describes input blankness, not content stripped by HTML sanitization.
- superset/mcp_service/dashboard/schemas.py:1531 — not affected: duplicate_dashboard already distinguishes originally blank input from stripped-only content; no runtime reclassification needed.
- superset/mcp_service/dashboard/schemas.py:884 — not affected: generate_dashboard rejects stripped-only content as unsafe_text; its optional blank-input behavior is intentionally unchanged.
- superset/mcp_service/dashboard/schemas.py:1050 — not affected: update_dashboard also rejects stripped-only content as unsafe_text.
- superset/mcp_service/chart/schemas.py:6369 — not affected: shared chart-name validation rejects stripped-only content as unsafe_text for both creation and updates.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "rebenitez1802 (via GitHub)" <gi...@apache.org>.
rebenitez1802 commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4350189772
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,29 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # HTML tag-open states require an ASCII letter, slash, bang or question
Review Comment:
**🟢 Low — Consider an allowlist for the `<` restore (hardening)**
This denylist matches the HTML tokenizer's tag-open rule for the value as stored, but it emits a raw `<` before non-ASCII letters that case-fold to ASCII:
- `Q3 <ſcript src=//e.example/x.js` (U+017F) is stored as-is and becomes `<SCRIPT SRC=…` under `.toUpperCase()`.
- js-xss lowercases a KELVIN SIGN (U+212A) tag name, so `x <\u212Abd title="y` in a `tooltipHtml` cell becomes a real `<kbd>` that swallows the rest of the row.
Base kept both escaped. I didn't find a sink that executes script this way, and REST already stores raw titles, so this is defense in depth only. An allowlist keeps every literal-comparison case (`<30`, `<$1M`, `<3`, `< 10`, `<=`, `<-`, `A <> B`) and passes the same tests:
```python
re.sub(r"<(?=[\d\s$€£¥%+=.,:;)\]&-]|$)", "<", cleaned)
```
(`&` covers a following escaped character, such as the `>` in `A <> B`.)
##########
docs/developer_docs/extensions/mcp.md:
##########
@@ -28,6 +28,17 @@ under the License.
Model Context Protocol (MCP) integration allows extensions to register custom AI agent capabilities that integrate seamlessly with Superset's MCP service. Extensions can provide both **tools** (executable functions) and **prompts** (interactive guidance) that AI agents can discover and use.
+## Chart and dashboard titles
+
+MCP chart names and dashboard titles preserve literal comparisons such as
+`Users aged <30`, `Revenue <$1M`, and `Love <3 charts`. HTML tags are stripped;
Review Comment:
**🟢 Low — Literal `<` now truncates Bullet/Rose tooltips (follow-up)**
These literals are now stored raw, but two ECharts tooltips run plain text through `sanitizeHtml` (js-xss with `stripIgnoreTag`) instead of escaping it: the Bullet range-label tooltip (`plugin-chart-echarts/src/Bullet/transformProps.ts:231`) and the Rose series tooltips (`Rose/transformProps.ts:136,183`). A `range_labels` value of `Users <30` renders as `Range: Users ` and a series named `Love <3 charts` as `Love ` (checked in jsdom with Superset's js-xss config); base's escaped `<30` happened to display correctly there. Labels typed in Explore already hit this, so not a blocker here, but worth a follow-up to HTML-escape those text fragments instead of filtering them.
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1065,17 +1069,17 @@ def _detect_dashboard_title_sanitization(cls, data: Any) -> Any:
@field_validator("dashboard_title")
@classmethod
- def sanitize_dashboard_title(cls, v: str | None) -> str | None:
- """Sanitize dashboard title to prevent XSS."""
- if v is None or v == "":
+ def normalize_blank_dashboard_title(cls, v: str | None) -> str | None:
+ """Reject blank updates; nonblank titles are sanitized above."""
+ if v is None:
return v
- return sanitize_user_input(
- v, "Dashboard title", max_length=500, allow_empty=True
- )
+ if not v.strip():
+ raise PydanticCustomError("empty_text", "dashboard_title cannot be empty")
Review Comment:
**🟢 Low — Add an UPDATING.md entry for the MCP contract changes**
Rejecting blank renames is a behavior change: base let `""` through and `update_dashboard` persisted it (it writes any non-null title). Together with `chart_name`'s published `maxLength` dropping from 255 to 250 and the new 250 cap on `theme_name`, MCP clients see a stricter contract. UPDATING.md already logs comparable MCP changes under `## Next`, e.g.:
```md
- MCP `update_dashboard` rejects blank or whitespace-only `dashboard_title`
values with "Text must not be empty"; omit the field to keep the stored title.
MCP chart names and theme names are capped at 250 characters, matching their
model columns.
```
##########
docs/developer_docs/extensions/mcp.md:
##########
@@ -587,3 +598,17 @@ governance concern from layout/theme/metadata edits.
- **[Development](./development.md)** - Project structure, APIs, and dev workflow
- **[Security](./security.md)** - Security best practices for extensions
+
+## Object-name validation
Review Comment:
**🟢 Low — Built-in tool docs land on the extension-authoring page**
This section sits after "Next Steps", and together with "Chart and dashboard titles" (line 31) it documents built-in tool behavior on the page for extension authors. Most of it is already in the new admin section (`docs/admin_docs/configuration/mcp-server.mdx`, "Title validation errors"). Consider moving the remaining details (theme, saved-query, SQL Lab and slug caps; trim-before-length) there, or at least placing this section above "Next Steps".
##########
tests/unit_tests/mcp_service/utils/test_sanitization.py:
##########
@@ -903,3 +904,95 @@ def test_data_label_followed_by_control_whitespace_is_preserved(
"""Whitespace after a comma-free data: label may be a tab or line break."""
value = f"Substitute data:{separator}Jira support tickets"
assert sanitize(value) == value.replace("\r\n", "\n")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "5 < 10",
+ "A < B",
+ "A <",
+ "A <> B",
+ ],
+)
+def test_strip_html_tags_preserves_non_tag_less_than(value: str) -> None:
+ """Preserve display text without decoding tag-opening brackets."""
+ assert _strip_html_tags(value) == value.replace(">", ">")
Review Comment:
Companion to the `_strip_html_tags` suggestion: this assertion pins the `<`/`>` asymmetry. With both applied, the touched MCP test files pass locally (1,742 passed).
```suggestion
"A <> B",
"Users aged >30",
"Revenue\u00a0>\u00a0$1M",
],
)
def test_strip_html_tags_preserves_non_tag_less_than(value: str) -> None:
"""Preserve display text without decoding tag-opening brackets."""
assert _strip_html_tags(value) == value
```
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,29 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # HTML tag-open states require an ASCII letter, slash, bang or question
+ # mark. Preserve literal comparisons like <30 and <$1M, but never decode
+ # a tag opener reconstructed by stripping intervening markup.
+ # Normalize removable characters before deciding whether a bracket is safe;
+ # otherwise a later Unicode strip could turn <\u200bscript into markup.
+ cleaned = _remove_dangerous_unicode(cleaned)
+ return re.sub(r"<(?![A-Za-z/!?])", "<", cleaned).replace("&", "&")
Review Comment:
**🟡 Medium — `>`/NBSP still escaped, and length caps now measure the escaped value**
This restores `<` but still emits `>` as `>` and U+00A0 as ` `. Since the before-validators now write the sanitized value back (`chart/schemas.py:6381`, `dashboard/schemas.py:1061`), `Field(max_length)` measures the escaped string:
- `"x" * 247 + ">"` (248 chars) fails `generate_chart` (even with `save_chart=False`) and `update_chart` with `string_too_long`; base accepted it (and stored 251 chars against `String(250)`).
- `update_dashboard` rejects a 500-char title containing `>` the same way, while `generate_dashboard`/`duplicate_dashboard` (no Field cap) store it as 503 chars against `String(500)`.
- Literal comparisons are one-sided: `Users aged >30` is stored as `Users aged >30` with a "modified during sanitization" warning, and filter value `>5` is rejected (the `;` in `>` trips the shell-character check) while `<5` passes.
Neither character can open a tag, and restoring them means sanitized output is never longer than the input:
```suggestion
# ">" and NBSP can never open a tag; restore them so plain text such as
# "Revenue > $1M" is stored as typed and never outgrows the length caps.
return (
re.sub(r"<(?![A-Za-z/!?])", "<", cleaned)
.replace(">", ">")
.replace(" ", "\u00a0")
.replace("&", "&")
)
```
Paired test update on `test_strip_html_tags_preserves_non_tag_less_than` in a separate comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4354259962
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,36 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # Restore brackets only before comparison punctuation, numbers or whitespace.
+ # Non-ASCII letters can case-fold into tag names in downstream renderers;
+ # leave those and reconstructed tag openers escaped.
+ # Normalize removable characters before deciding whether a bracket is safe;
+ # otherwise a later Unicode strip could turn <\u200bscript into markup.
+ cleaned = _remove_dangerous_unicode(cleaned)
+ # Greater-than signs and NBSP cannot open tags. Restore them so plain text
+ # neither changes on display nor outgrows the model-column length limits.
+ return (
+ re.sub(r"<(?=[\d\s$€£¥%+=.,:;)\]&-]|$)", "<", cleaned)
Review Comment:
Fixed in 0c05b084da93e460e38157f057f171f40479d721. I verified the suggested allowlist against the report-title normalization path: control whitespace stays escaped before non-whitespace content; trailing whitespace and literal comparisons retain their existing behavior.
Regression tests: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_title_control_whitespace_cannot_form_slack_markup` covers chart create (including unsaved), chart update, and all three dashboard title schemas, four Slack control forms, six whitespace characters, and resubmission. `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_control_whitespace_warning_wrapper_keeps_slack_markup_inert` pins the exact normalized escaped output and warning for literal and entity-encoded TAB/LF/CR. The selected new tests produced 87 failures against the reviewed sanitizer and pass with this commit (nh3 0.3.7, pydantic 2.14.1, fastmcp 4.1.2); the two touched files pass 1,019 tests. Filter rejection and safe trailing whitespace are separately pinned.
Siblings checked:
- superset/mcp_service/utils/sanitization.py:39 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/utils/sanitization.py:233 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/utils/sanitization.py:261 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/utils/sanitization.py:363 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:879 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1003 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1011 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1132 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1143 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1144 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:1211 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:2761 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:3155 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:4628 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:4637 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/chart/schemas.py:6369 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 0c05b084da93e460e38157f057f171f40479d721
- superset/mcp_service/utils/sanitization.py:105 — not affected: the stability check delegates to the same stripping helper; the new model resubmission assertions pass.
- superset/utils/file.py:47 — not affected: control stripping is intentional and unchanged; regression assertions apply this function to the stored MCP title.
- superset/commands/report/execute.py:1656 — not affected: chart and dashboard report names use sanitize_title; MCP titles reach it with the bracket escaped.
- superset/reports/notifications/slack_mixin.py:50 — not affected: both Slack notification transports share this template; the MCP title stays escaped before interpolation.
- superset/mcp_service/utils/error_builder.py:54 — not affected: independent error-context sanitizer, not a caller of the changed helper or a persisted title.
- superset/mcp_service/utils/sanitization.py:465 — not affected: SQL-expression validation does not call the HTML-stripping helper.
Search: `rg -n '_strip_html_tags\(|sanitize_user_input\(|sanitize_user_input_with_changes\(|sanitize_filter_value\(' superset/mcp_service`; `rg -n 'sanitize_title' superset`; `rg -n 'SlackMixin|content.name' superset/reports/notifications`.
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,683 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+def test_name_contract_changes_have_upgrade_guidance() -> None:
+ """Clients need migration guidance for blank renames and tighter name caps."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ next_release = (
+ (root / "UPDATING.md").read_text().split("## Next", 1)[1].split("\n## ", 1)[0]
+ )
+ assert (
+ "`update_dashboard` rejects blank or whitespace-only `dashboard_title`"
+ in next_release
+ )
+ assert "chart names and theme names are capped at 250 characters" in next_release
+ assert "omit the field to keep the stored title" in next_release
+
+
Review Comment:
Fixed in 0c05b084da93e460e38157f057f171f40479d721. I verified the release-cut example and removed `test_name_contract_changes_have_upgrade_guidance` as suggested. The upgrade note remains in UPDATING.md; unit tests no longer require it to stay under `## Next` forever.
Regression reproduction: I inserted a release heading immediately after `## Next`, restoring the reviewed test for the before run. The selected suite failed only `test_name_contract_changes_have_upgrade_guidance` (1 failed, 21 passed). With that test removed and the same release heading retained, it passed (21 passed). I then restored UPDATING.md unchanged. The PR-added `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_update_dashboard_blank_title_wire_reason`, `test_chart_name_model_column_boundary`, and `test_theme_name_model_column_boundary` keep pinning the runtime contract; those 21 cases intentionally pass in both runs. The removed documentation assertion, not runtime validation, is the release-cut regression. The complete two touched files pass 1,019 tests.
Siblings checked:
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py — fixed in 0c05b084da93e460e38157f057f171f40479d721
- UPDATING.md:25 — not affected: the migration guidance is retained and may move under a version heading at release.
- docs/admin_docs/configuration/mcp-server.mdx:2433 — not affected: permanent administrator guidance does not depend on release headings.
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:792 — not affected: blank-rename wire tests validate behavior, not documentation placement.
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:722 — not affected: chart-name limits are asserted against the persisted model column.
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:773 — not affected: theme-name limits are asserted against the persisted model column.
Search: `rg -n 'UPDATING.md|## Next' tests/unit_tests` found no other unit test reading the Next section (other hits are comments/docstrings); `git show d76b896c9c -- UPDATING.md` confirms the release-heading insertion pattern.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi merged PR #45575:
URL: https://github.com/apache/superset/pull/45575
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6322095238
Local end-to-end check at 409886ec39d83e61eea05ce9b29c89e279c2000a, compared with the merge base cdc9430597c84ce1c89b400cf3215247b372d657. I ran the MCP service (`superset mcp run`, `call_tool` over streamable HTTP) on example data as Admin, Alpha and Gamma users, and read every saved title back from the metadata DB.
Result: looks good to ship.
- Over-limit titles (501/600-char dashboard titles, 251–600-char chart names, including the `name`/`slice_name`/`title` aliases) report "String exceeds the allowed maximum length" in 66/66 cases. The merge base reported "Contains disallowed content" for dashboards and `generate_chart`. The error shape is unchanged.
- A 250-character chart name saves at 250 characters through all four aliases. 251 and 255 are rejected with no row written and the stored name unchanged. These are the only outcome changes from the merge base: 30 of 303 paired calls.
- Blank or whitespace-only titles/names on `duplicate_dashboard` (including its aliases), `create_virtual_dataset`, `update_dataset`, `create_dataset_metric`, `update_dataset_metric`, `create_theme` and whitespace-only `save_sql_query` labels report "Text must not be empty" at the right field.
- `<script>`, `javascript:` and `data:text/html,` titles are still rejected (45/45, same class as the merge base). Valid titles with curly quotes, apostrophes, `&`, emoji and surrounding spaces save as before.
Small things I noticed, none blocking:
1. A 250-character chart name sent with leading/trailing spaces is now rejected, although the trimmed name would fit (the merge base saved it at 250). `Field(max_length=250)` checks the raw value, while dashboard titles are trimmed before the length check. Writing the trimmed value back in the chart-name before-validator would make the two consistent.
2. `create_theme` has no length cap, but `Theme.theme_name` is `String(250)`. A 310-character name saved on SQLite, so on PostgreSQL/MySQL it would fail at the database instead of returning a length reason. This was already the case before this PR.
3. `save_sql_query` with `label: ""` reports "String is shorter than the allowed minimum", while whitespace-only reports "Text must not be empty". This matches the docs, which only cover whitespace-only labels.
Not run: a real LLM in the loop, PostgreSQL/MySQL metadata DB, deployed auth modes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6325980060
## CodeAnt PR Risk: Low Risk
- The PR appears safe to merge; no actionable issues were identified in the review.
**Assessed commit:** `94163c810083`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6373184508
@rebenitez1802 Thank you for the approval and the detailed verification. I read the approval body; it contains no additional requests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6372018523
Thanks @rebenitez1802 for the verification and approval. I read the approval body; it contains no additional requests. @sadpandajoe, the raw-input versus stored-title length question is being tracked in its inline thread.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4367066006
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
You're right: my earlier theme sibling entry was incorrect. Fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00; final head 57260a2b4544fb3c71004775194a5d8ca897dfed (documentation/test alignment): create_theme rejects blank theme_name before the 250-character cap, including the reported 300-space input. I also gave create_dataset_metric/update_dataset_metric metric_name and update_dataset table_name the same blank-first behavior, rather than weakening the documentation promise. Nonblank names retain their whitespace, length limits, and malformed-input errors; omitted updates and explicit invalid null names keep their existing behavior.
Regression tests added in tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
- test_documented_blank_errors_precede_length systematically covers all eight request fields with a documented blank-error promise: update_dashboard.dashboard_title (500), duplicate_dashboard.dashboard_title (500), create_virtual_dataset.dataset_name (250), create_theme.theme_name (250), create_dataset_metric.metric_name (255), update_dataset_metric.metric_name (255), update_dataset.table_name (250), and save_sql_query.label (256). Each is tested with " " * (cap + 1) as str, bytes and bytearray, plus Unicode whitespace. The four affected requests produce 24 failures before this commit and pass after; the other 24 cases are already-passing sibling controls.
- test_required_name_over_cap_blank_wire_reason pins the exact MCP response, including "Text must not be empty" at the corresponding name field, for cap+1 and cap+50 blanks. Eight cases fail before/pass after (including theme_name with 300 spaces); four existing-behavior sibling controls pass both times.
- test_documented_name_nonblank_length_boundary, test_literal_names_keep_nonblank_whitespace, and test_literal_names_reject_malformed_inputs retain 84 passing controls for exact/over-limit nonblank names, whitespace preservation, and native field-located type/UTF-8 errors.
The same 144-case regression suite ran in Docker against untouched source at 705c6f0bc395800d6b5fee03d5bef0a9830b1852 (32 failed / 112 passed) and this commit (144 passed). Command: `python -m pytest -q tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py -k 'documented_blank_errors_precede_length or documented_name_nonblank_length_boundary or required_name_over_cap_blank_wire_reason or literal_names_'`.
Full Docker MCP run: 13,245 passed / 12 skipped with `python -m pytest -n 2 --dist loadfile tests/unit_tests/mcp_service -m 'not manual and not llm_compliance' --cache-clear -o cache_dir=/tmp/pytest-cache --maxfail=20`. The touched regression file passed all 1,737 tests. The updated test_builtin_name_validation_documented_for_administrators also fails against the original documentation and passes against the clarified documentation; its whitespace-normalized assertion avoids depending on Markdown line wrapping.
Changed-file pre-commit and explicit `pre-commit run mypy` passed; the three existing frontend Jest suites passed (32 tests). Real-LLM checks were excluded (OpenRouter disabled).
I searched `rg -n 'max_length|empty_text' superset/mcp_service -g '*schemas.py'`, inventoried all 140 explicit max_length field declarations (including nested/response schemas), compared the documentation's named blank-error contracts, and searched all callers of the changed request models. The eight promised fields and adjacent paths are all listed below.
Siblings checked:
- superset/mcp_service/theme/schemas.py:138 — fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00 (CreateThemeRequest.theme_name, cap 250).
- superset/mcp_service/dataset/schemas.py:701 — fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00 (DatasetMetricProperties.metric_name, shared blank-first validator, cap 255).
- superset/mcp_service/dataset/schemas.py:809 — fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00 (UpdateDatasetMetricRequest.metric_name inherits that validator).
- superset/mcp_service/dataset/schemas.py:820 — fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00 (CreateDatasetMetricRequest.metric_name inherits that validator despite overriding the field).
- superset/mcp_service/dataset/schemas.py:1025 — fixed in 0c80cb2f93830711849b06965c4e28a3f4ce2f00 (UpdateDatasetRequest.table_name, cap 250).
- superset/mcp_service/dataset/schemas.py:580 — not affected: CreateVirtualDatasetRequest.dataset_name (cap 250) already decodes bytes, rejects blanks and trims before its cap; included in the same regression sweep.
- superset/mcp_service/dashboard/schemas.py:926 — not affected: UpdateDashboardRequest.dashboard_title (cap 500) already rejects blanks before its cap; included in the same regression sweep.
- superset/mcp_service/dashboard/schemas.py:1487 — not affected: DuplicateDashboardRequest.dashboard_title (cap 500) already rejects blanks before its cap; included in the same regression sweep.
- superset/mcp_service/sql_lab/schemas.py:233 — not affected: SaveSqlQueryRequest.label (cap 256) already decodes bytes and rejects blanks before its cap; included in the same regression sweep.
- superset/mcp_service/chart/schemas.py:6352 — not affected: ChartNameMixin already normalizes blank chart_name to None before its cap for both GenerateChartRequest and UpdateChartRequest; test_blank_titles_normalize_before_length covers strings, bytes, bytearrays and all four aliases.
- superset/mcp_service/dashboard/schemas.py:781 — not affected: GenerateDashboardRequest uses its documented optional-title fallback rather than an empty-text error; test_blank_titles_normalize_before_length covers strings, bytes, bytearrays and aliases.
- superset/mcp_service/dataset/schemas.py:506 — not affected: CreateDatasetRequest.table_name trims before its cap and uses its min_length error for blanks, not the blank-error promise naming create_virtual_dataset and update_dataset; schema/catalog blanks normalize to None before their caps.
- superset/mcp_service/dataset/schemas.py:458 — not affected: nested CreateDatasetMetric.metric_name has no max_length and is not the create_dataset_metric/update_dataset_metric tool request named in the documentation.
- superset/mcp_service/sql_lab/schemas.py:301 — not affected: OpenSqlLabRequest.title normalizes blanks to None before its cap, not the blank-error contract for save_sql_query.label.
- superset/mcp_service/dashboard/schemas.py:1093 — not affected: UpdateDashboardRequest.slug has a separate blank-clears-slug contract and normalizes before its cap, not the dashboard_title blank-error promise.
- superset/mcp_service/theme/tool/create_theme.py:61 — not affected: consumes the validated CreateThemeRequest; no separate raw-name normalization path.
- superset/mcp_service/dataset/tool/create_dataset_metric.py:47 — not affected: consumes the validated CreateDatasetMetricRequest and its updates(), with no separate raw-name normalization path.
- superset/mcp_service/dataset/tool/update_dataset_metric.py:110 — not affected: consumes the validated UpdateDatasetMetricRequest and its updates(), with no separate raw-name normalization path.
- superset/mcp_service/dataset/tool/update_dataset.py:80 — not affected: consumes the validated UpdateDatasetRequest and its updates(), with no separate raw-name normalization path.
- superset/themes/schemas.py — not affected: the REST theme endpoint uses separate Marshmallow validation; the documented promise here is for MCP requests.
- superset/datasets/schemas.py — not affected: REST dataset/metric schemas do not invoke these MCP validators; their validation contract is unchanged.
- docs/admin_docs/configuration/mcp-server.mdx:2457 — fixed in 57260a2b4544fb3c71004775194a5d8ca897dfed (blank-first ordering is explicit, nonblank whitespace preservation is precise, and the comparison names virtual datasets rather than physical table names).
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:1376 — fixed in 57260a2b4544fb3c71004775194a5d8ca897dfed (the documentation assertion checks the clarified contract and ignores Markdown line wrapping).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4344467286
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,603 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ ["Users aged <30", "Revenue <$1M", "Love <3 charts", "Users aged <30 & “VIP” 📈"],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+ ],
+)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_use_single_sanitizer_result(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Shared-sanitizer siblings preserve comparisons and never re-sanitize output."""
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ sql_identifier = field in ("column", "temporal_column", "name")
+ expected: str | int | float | None
+ try:
+ if model is FilterConfig and field == "value":
+ from superset.mcp_service.utils.sanitization import sanitize_filter_value
+
+ expected = sanitize_filter_value(value)
+ else:
+ expected = sanitize_user_input(
+ value,
+ "Value",
+ max_length=500,
+ check_sql_keywords=sql_identifier,
+ allow_empty=True,
+ )
+ except ValueError:
Review Comment:
Fixed in 9b87c3b399ca023b232bd3f356b9273ce9d4ca24. I split accepted and rejected inputs rather than deriving expectations from the sanitizer.
Regression test: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_sibling_fields_preserve_literal_comparison` requires successful validation and the exact literal `Users aged <30` across all 14 sibling fields, including identifiers. With only the literal-`<` restoration removed, all 14 cases fail; restored, all 14 pass. The old test still passed all 42 cases under that same mutation, reproducing the coverage gap. `test_sibling_fields_reject_reconstructed_tag` separately pins all 28 rejections to `unsafe_text` and the exact canonical field location. The combined restored run passes all 42 cases.
Siblings checked:
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:1004 — fixed in 9b87c3b399ca023b232bd3f356b9273ce9d4ca24
- superset/mcp_service/chart/schemas.py:879 — not affected: production code unchanged; temporal_column literal acceptance and typed rejection are pinned by the split tests.
- superset/mcp_service/chart/schemas.py:1003 — not affected: ColumnRef name and label both covered by the split tests.
- superset/mcp_service/chart/schemas.py:1132 — not affected: filter column and value both covered, including the separate filter sanitizer.
- superset/mcp_service/chart/schemas.py:1211 — not affected: Gantt sort column covered by the split tests.
- superset/mcp_service/chart/schemas.py:2761 — not affected: Sunburst time_range covered by the split tests.
- superset/mcp_service/chart/schemas.py:3155 — not affected: interactive-pivot comparison_period covered by the split tests.
- superset/mcp_service/chart/schemas.py:4628 — not affected: Bullet time_range and all three label-list fields covered by the split tests.
- superset/mcp_service/dashboard/schemas.py:1393 — not affected: both certification fields covered by the split tests.
- tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:958 — not affected: test_title_sanitized_once asserts invocation count without catching rejection; literal titles have separate exact-output tests.
- tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py:1206 — not affected: revalidation test asserts one invocation and storage writeback without catching rejection; separate storage round-trip tests pin literal titles.
- tests/unit_tests/mcp_service/test_logging_filters.py:67 — not affected: ValueError catch constructs logging exception metadata, not a validation expectation.
Search: `rg -n 'sanitize_user_input\(|sanitize_filter_value\(' superset/mcp_service` and `rg -n 'expected = sanitize|except ValueError:' tests/unit_tests/mcp_service`.
##########
docs/admin_docs/configuration/mcp-server.mdx:
##########
@@ -2424,3 +2424,20 @@ Context names are returned verbatim per the Tool Result Value Contract.
"Did you mean" column candidates also preserve dataset spelling, including
quotes and ampersands, with a 200-character bound per candidate. Use
`get_dataset_info` for the complete schema.
+
+### Title validation errors
+
+Rejected MCP titles report a field-specific reason without echoing the input.
+Titles exceeding 500 characters for dashboards or 250 characters for charts
+report "String exceeds the allowed maximum length". `duplicate_dashboard`
+requires a non-blank title and reports "Text must not be empty" for blank or
+whitespace-only input. A title containing only removed HTML/script content
+(such as `<script>alert(1)</script>`) reports "Contains disallowed content"
+(`unsafe_text`), not an empty-text error. Optional titles retain their existing
Review Comment:
Fixed in 9b87c3b399ca023b232bd3f356b9273ce9d4ca24. Rejecting blank renames is intentional: the PR description explicitly calls for it, and the update tool writes every non-null title. I limited the unchanged empty-value behavior to creation and documented blank/whitespace-only dashboard rename rejection plus omission preserving the stored title. No runtime behavior changed in this commit.
Regression test: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_update_dashboard_blank_title_wire_reason` covers empty/whitespace input through all three aliases. Against the base dashboard schema, all 6 cases fail; restored to the PR schema, all 6 pass. A documentation contract assertion also fails on the preceding paragraph and passes on this wording. The scoped MCP suite passes 1,070 tests.
Siblings checked:
- docs/admin_docs/configuration/mcp-server.mdx:2436 — fixed in 9b87c3b399ca023b232bd3f356b9273ce9d4ca24
- docs/developer_docs/extensions/mcp.md:610 — not affected: already documents explicit blank dashboard rename rejection and omission preserving the existing value.
- superset/mcp_service/dashboard/schemas.py:1072 — not affected: intentional blank rename rejection remains unchanged and is covered by the six wire cases.
- superset/mcp_service/dashboard/tool/update_dashboard.py:186 — not affected: writes only non-null titles; omitted title remains unchanged.
- superset/mcp_service/dashboard/schemas.py:907 — not affected: creation retains its existing optional-title empty-value behavior.
- superset/mcp_service/dashboard/schemas.py:1553 — not affected: duplication still requires a nonblank title, already documented and covered by test_duplicate_dashboard_empty_title_wire_reason.
- superset/mcp_service/chart/schemas.py:6393 — not affected: optional chart-name normalization remains unchanged; this correction describes dashboard renames only.
Search: `rg -n 'Optional titles|empty-value behavior|blank.*rename|Text must not be empty' docs/admin_docs/configuration/mcp-server.mdx docs/developer_docs/extensions/mcp.md` and `rg -n 'dashboard_title' superset/mcp_service/dashboard/tool/update_dashboard.py`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366897544
##########
superset-frontend/plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts:
##########
@@ -193,3 +196,27 @@ test('renders when __timestamp is serialized as a non-epoch string', () => {
expect(seriesNames).toEqual(['East', 'West']);
expect(series[0].data.map((d: any) => d.value)).toEqual([30, 10]);
});
+
+test.each([true, false])(
+ 'escapes literal series text in Rose tooltips (rich=%s)',
+ richTooltip => {
+ const name = 'Love <3 charts & <img src=x>';
+ const props = new ChartProps({
+ width: 800,
+ height: 600,
+ formData: { ...formData, richTooltip },
Review Comment:
Both parametrized tooltip modes keep `dateTimeFormat: 'smart_date'`, so the new `escapeHtml(period.label)` calls in the rich-tooltip and plain-tooltip formatters never see markup. Removing either escape would still pass; only the drilled test covers the third site. Could this test set `dateTimeFormat` to something like `'<b>period</b>'` and assert the label text survives literally with exactly one structural `<b>`?
##########
superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts:
##########
@@ -424,3 +424,38 @@ test('keeps exact-case dimensions and uses per-index fallbacks for short labels'
.map(series => series.markLine?.data[0].label.formatter()),
).toEqual(['stretch', '260.0']);
});
+
+test('escapes literal comparison text in every Bullet tooltip', () => {
+ const label = 'Users <30 & <img src=x>';
+ const metric = 'Total <3';
Review Comment:
The metric `Total <3` is parsed as plain text even when `escapeHtml(metricLabel)` is removed, because `<3` is not a tag. The assertion on `textContent` still passes, so a regression that drops that escape goes unnoticed while the other labels use `<img src=x>`. Could the metric include an allowed tag such as `<b>Total</b>` and assert the literal text survives in the first tooltip?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366160751
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,789 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_escaped_title_still_fits_model_column(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Conservative bracket escaping cannot bypass a persisted title's length cap."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2) + "<ſ"
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("whitespace", ["\t", "\n", "\r", "\v", "\f", "\x85"])
+@pytest.mark.parametrize(
+ "control",
+ ["!channel", "@U123", "#C123|general", "https://example.invalid|Open dashboard"],
+)
+def test_title_control_whitespace_cannot_form_slack_markup(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ whitespace: str,
+ control: str,
+) -> None:
+ """Report title normalization must not join brackets into Slack controls."""
+ from superset.utils.file import sanitize_title
+
+ value = f"Q3 <{whitespace}{control}>"
+ request = model.model_validate({**payload, field: value})
+ stored = getattr(request, field)
+ assert "<" not in sanitize_title(stored)
+ assert getattr(model.model_validate(request.model_dump()), field) == stored
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("alias_index", range(4))
+@pytest.mark.parametrize("length_delta", [-5, 0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_markup_title_length_uses_sanitized_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ alias_index: int,
+ length_delta: int,
+ padding: str,
+) -> None:
+ """Markup is not part of the persisted title's character budget."""
+ aliases = (
+ ("chart_name", "name", "title", "slice_name")
+ if field == "chart_name"
+ else ("dashboard_title", "title", "name", "dashboard_title")
+ )
+ limit = 250 if field == "chart_name" else 500
+ text = "x" * (limit + length_delta)
+ value = "<b>" + padding + text + padding + "</b>"
+ if length_delta > 0:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, aliases[alias_index]: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate({**payload, aliases[alias_index]: value})
+ assert getattr(request, field) == text
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [case for case in _SIBLING_SANITIZATION_CASES if case[2] != "value"],
+)
+@pytest.mark.parametrize("extra", [0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_sibling_sanitized_length_budget(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ extra: int,
+ padding: str,
+) -> None:
+ """All callers of the shared text sanitizer enforce the final text cap."""
+ limits = {
+ "certified_by": 500,
+ "certification_details": 5000,
+ "temporal_column": 255,
+ "name": 255,
+ "label": 500,
+ "column": 255,
+ "time_range": 1000,
+ "comparison_period": 100,
+ "range_labels": 200,
+ "marker_labels": 200,
+ "marker_line_labels": 200,
+ }
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ text = "x" * (limits[field] + extra)
+ value = "<b>" + padding + text + padding + "</b>"
+ if extra:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert getattr(request, field) == (
+ [text] if field.endswith("_labels") else text
+ )
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ case
+ for case in _SIBLING_SANITIZATION_CASES
+ if case[2] != "value" and not case[2].endswith("_labels")
+ ],
+)
+@pytest.mark.parametrize("value", [b"<b>Safe</b>", bytearray(b"<b>Safe</b>")])
Review Comment:
This parametrization covers sibling configuration and certification fields, but not the chart name or title models. `UpdateChartRequest(identifier=1, chart_name=b"Safe <b>title</b>")` skips the string-only `before` validator, pydantic then decodes the bytes, and `normalize_blank_chart_name` only checks blankness, so the stored name keeps `<b>` (it was sanitized to `Safe title` before this change). Could `chart_name` (and the dashboard title) be added with bytes/bytearray inputs asserting the sanitized value, or the after-validator sanitize as well?
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
A whitespace-only `chart_name` longer than 250 characters now fails with `string_too_long`: `Field(max_length=250)` runs before this validator, and the model-level sanitizer returns early for blank input. For example `generate_chart` with `chart_name=" " * 251` used to normalize to `None` and fall back to the generated name under the old 255 cap. Should blank values be collapsed to `None` in the `mode="before"` validator, ahead of the length constraint, so the documented trim-before-length behavior holds here too?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366925344
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
Correction to my reply above: the sibling entry `superset/mcp_service/dataset/schemas.py:506 — fixed` is only true for `table_name`. In `CreateDatasetRequest`, the `schema_`/`catalog` before-validator `_normalize_optional_str` (`superset/mcp_service/dataset/schemas.py:554`) still handles only `str`, so a whitespace-only bytes value longer than 250 (`schema_=b" " * 251`) still fails with `string_too_long` instead of normalizing to `None` as the string input does. Not fixed yet at 746c57391cecb0fba4771a678914bfa1131efd73.
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,789 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_escaped_title_still_fits_model_column(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Conservative bracket escaping cannot bypass a persisted title's length cap."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2) + "<ſ"
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("whitespace", ["\t", "\n", "\r", "\v", "\f", "\x85"])
+@pytest.mark.parametrize(
+ "control",
+ ["!channel", "@U123", "#C123|general", "https://example.invalid|Open dashboard"],
+)
+def test_title_control_whitespace_cannot_form_slack_markup(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ whitespace: str,
+ control: str,
+) -> None:
+ """Report title normalization must not join brackets into Slack controls."""
+ from superset.utils.file import sanitize_title
+
+ value = f"Q3 <{whitespace}{control}>"
+ request = model.model_validate({**payload, field: value})
+ stored = getattr(request, field)
+ assert "<" not in sanitize_title(stored)
+ assert getattr(model.model_validate(request.model_dump()), field) == stored
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("alias_index", range(4))
+@pytest.mark.parametrize("length_delta", [-5, 0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_markup_title_length_uses_sanitized_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ alias_index: int,
+ length_delta: int,
+ padding: str,
+) -> None:
+ """Markup is not part of the persisted title's character budget."""
+ aliases = (
+ ("chart_name", "name", "title", "slice_name")
+ if field == "chart_name"
+ else ("dashboard_title", "title", "name", "dashboard_title")
+ )
+ limit = 250 if field == "chart_name" else 500
+ text = "x" * (limit + length_delta)
+ value = "<b>" + padding + text + padding + "</b>"
+ if length_delta > 0:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, aliases[alias_index]: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate({**payload, aliases[alias_index]: value})
+ assert getattr(request, field) == text
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [case for case in _SIBLING_SANITIZATION_CASES if case[2] != "value"],
+)
+@pytest.mark.parametrize("extra", [0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_sibling_sanitized_length_budget(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ extra: int,
+ padding: str,
+) -> None:
+ """All callers of the shared text sanitizer enforce the final text cap."""
+ limits = {
+ "certified_by": 500,
+ "certification_details": 5000,
+ "temporal_column": 255,
+ "name": 255,
+ "label": 500,
+ "column": 255,
+ "time_range": 1000,
+ "comparison_period": 100,
+ "range_labels": 200,
+ "marker_labels": 200,
+ "marker_line_labels": 200,
+ }
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ text = "x" * (limits[field] + extra)
+ value = "<b>" + padding + text + padding + "</b>"
+ if extra:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert getattr(request, field) == (
+ [text] if field.endswith("_labels") else text
+ )
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ case
+ for case in _SIBLING_SANITIZATION_CASES
+ if case[2] != "value" and not case[2].endswith("_labels")
+ ],
+)
+@pytest.mark.parametrize("value", [b"<b>Safe</b>", bytearray(b"<b>Safe</b>")])
Review Comment:
Correction to my reply above: the sibling entry `superset/mcp_service/dataset/schemas.py:506 — fixed` is only true for `table_name`. The `schema_`/`catalog` before-validator `_normalize_optional_str` (`superset/mcp_service/dataset/schemas.py:554`) still handles only `str`, so bytes bypass it: `CreateDatasetRequest(database_id=1, table_name="t", schema_=b" public ")` keeps `" public "` (the string input gives `"public"`), `bytearray(b" ")` stays `" "` instead of `None`, and `b" " * 251` fails with `string_too_long`. Not fixed yet at 746c57391cecb0fba4771a678914bfa1131efd73.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4363273424
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -305,6 +339,19 @@ def sanitize_user_input(
value = _strip_html_tags(value)
value = _remove_dangerous_unicode(value)
+ # Reject rather than store tag-shaped text: a later sanitizer pass would
+ # decode and strip it, so the stored value would not be stable.
+ _check_stable_html(value, field_name)
+
+ # Conservative bracket escaping can expand text even after tags are removed.
+ # Enforce the storage cap for callers without a Pydantic Field length limit.
+ if len(value) > max_length:
Review Comment:
The cap is checked on the tag-stripped value before the callers' final `.strip()`, so whitespace that only exists because markup was removed still counts toward the limit. For example, `chart_name = "<b> " + "A" * 250 + " </b>"` strips to `" " + "A"*250 + " "` (252 chars), is rejected with `string_too_long`, and yet would store as a valid 250-character name after trimming; `duplicate_dashboard` with `"<b> " + "x" * 500 + " </b>"` fails the same way at 500. Could the length check run after the stripped value is trimmed so it matches the stored name? The docs sentence that says limits apply after trimming would then be accurate too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4344154231
##########
docs/admin_docs/configuration/mcp-server.mdx:
##########
@@ -2424,3 +2424,20 @@ Context names are returned verbatim per the Tool Result Value Contract.
"Did you mean" column candidates also preserve dataset spelling, including
quotes and ampersands, with a 200-character bound per candidate. Use
`get_dataset_info` for the complete schema.
+
+### Title validation errors
+
+Rejected MCP titles report a field-specific reason without echoing the input.
+Titles exceeding 500 characters for dashboards or 250 characters for charts
+report "String exceeds the allowed maximum length". `duplicate_dashboard`
+requires a non-blank title and reports "Text must not be empty" for blank or
+whitespace-only input. A title containing only removed HTML/script content
+(such as `<script>alert(1)</script>`) reports "Contains disallowed content"
+(`unsafe_text`), not an empty-text error. Optional titles retain their existing
Review Comment:
This closing sentence says optional titles keep their existing empty-value behavior, but `update_dashboard` now rejects `dashboard_title: ""` (and whitespace-only) with "Text must not be empty"; before this change that input passed validation. An operator reading this section would expect a blank rename to behave as it did. Should the sentence limit the unchanged behavior to creation and say that blank dashboard renames are now rejected?
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,603 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ ["Users aged <30", "Revenue <$1M", "Love <3 charts", "Users aged <30 & “VIP” 📈"],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+ ],
+)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_use_single_sanitizer_result(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Shared-sanitizer siblings preserve comparisons and never re-sanitize output."""
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ sql_identifier = field in ("column", "temporal_column", "name")
+ expected: str | int | float | None
+ try:
+ if model is FilterConfig and field == "value":
+ from superset.mcp_service.utils.sanitization import sanitize_filter_value
+
+ expected = sanitize_filter_value(value)
+ else:
+ expected = sanitize_user_input(
+ value,
+ "Value",
+ max_length=500,
+ check_sql_keywords=sql_identifier,
+ allow_empty=True,
+ )
+ except ValueError:
Review Comment:
`test_sibling_fields_use_single_sanitizer_result` takes its expected value from the sanitizer under test and treats any `ValueError` as an expected rejection. If the literal-`<` restoration in `_strip_html_tags` were reverted, `ColumnRef(name="Users aged <30")` would be rejected for the escaped ampersand, the helper would raise the same way, and the test would still pass, so the `<30` preservation for the identifier fields (`column`, `temporal_column`, `name`) is not pinned here. Could the inputs that should be accepted assert successful validation and the exact literal output, with the rejected inputs listed separately and asserting their error type and location?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4363520671
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -305,6 +339,19 @@ def sanitize_user_input(
value = _strip_html_tags(value)
value = _remove_dangerous_unicode(value)
+ # Reject rather than store tag-shaped text: a later sanitizer pass would
+ # decode and strip it, so the stored value would not be stable.
+ _check_stable_html(value, field_name)
+
+ # Conservative bracket escaping can expand text even after tags are removed.
+ # Enforce the storage cap for callers without a Pydantic Field length limit.
+ if len(value) > max_length:
Review Comment:
You're right. I fixed the ordering in 4818cc616fa9cc41abb782276c3d951cd033a978: the shared user-text sanitizer trims after tag/Unicode removal, before checking the final text cap. The independent raw-input resource bound and HTML/URL/event-handler/SQL safety checks remain in place.
Regression tests expanded in this commit:
- `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_markup_title_length_uses_sanitized_text`: padded markup at the 250/500-character boundary, all title aliases, chart generate/update and dashboard generate/update/duplicate. It asserts exact trimmed values and warnings, while over-limit values still report `string_too_long`.
- `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_sibling_sanitized_length_budget`: every sibling scalar/list field on the shared sanitize-plus-cap path, including certification, columns, time ranges and Bullet labels.
- `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_sanitized_length_budget`: both shared entry points, literal spaces, encoded spaces and NBSP at each supported cap.
Before the source change, this expanded test selection produced 153 failures and 323 passes; the failing padded boundary cases pass after the fix. Both touched modules pass all 1,516 tests in Docker. Existing unpadded-markup and over-limit guards still pass, preserving the earlier raw-versus-sanitized length correction. The Bullet/Rose Jest suites pass 32 tests. Scoped pre-commit passes, including mypy, Ruff and Pylint.
Siblings checked:
- superset/mcp_service/chart/schemas.py:883 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:1009 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:1021 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:1144 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:1227 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:2781 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:3177 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:4650 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:4664 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/schemas.py:6396 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/dashboard/schemas.py:1397 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/dashboard/schemas.py:1422 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/dashboard/schemas.py:1539 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/utils/sanitization.py:233 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/utils/sanitization.py:261 — fixed in 4818cc616fa9cc41abb782276c3d951cd033a978
- superset/mcp_service/chart/tool/generate_chart.py:255 — not affected: schema revalidation carries over the already-trimmed chart name
- superset/mcp_service/chart/tool/update_chart.py:907 — not affected: the shared UpdateChartRequest validates the name before this tool persists it
- superset/mcp_service/chart/validation/pipeline.py:326 — not affected: normalization carries over the already-trimmed chart name
- superset/mcp_service/dataset/schemas.py — not affected: names do not use HTML stripping; markup remains literal
- superset/mcp_service/sql_lab/schemas.py — not affected: labels and tab titles do not use HTML stripping
- superset/mcp_service/theme/schemas.py — not affected: theme names intentionally retain whitespace and do not use this sanitizer
- superset/mcp_service/utils/sanitization.py:368 — not affected: filter values have a separate raw-input cap and preserve literal value whitespace
- superset/mcp_service/utils/sanitization.py:470 — not affected: SQL expressions reject HTML rather than strip tags
- superset/mcp_service/utils/error_builder.py:54 — not affected: separate display-context helper, not persisted input validation
Search: `rg -n 'sanitize_user_input|sanitize_filter_value|sanitize_sql_expression' superset/mcp_service --glob '*.py'`; the repository-wide search finds no shared user-text callers outside MCP.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4362993943
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6377,15 +6367,18 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
return data
with field_validation_error("chart_name"):
sanitized, was_modified = sanitize_user_input_with_changes(
- raw, "Chart name", max_length=255, allow_empty=True
+ raw, "Chart name", max_length=250, allow_empty=True
Review Comment:
You're right: removed markup should not consume the stored-name budget. Fixed in 2ae7a389d2a298b45cbba8a388d99d94c50eb7c8, with byte-string coercion coverage in 335dbaf204c7684af3e990505949a35c61cee635. The shared user-text sanitizer now has a separate raw-input resource bound of 10,000 characters (or the field cap if larger), while the existing final-text limit still runs after sanitization. Scalar sibling field validators also sanitize before Pydantic's length check.
Regression tests added by this change:
- `test_markup_title_length_uses_sanitized_text`: the exact 245-character bold chart name, the 250-character boundary, all chart aliases, generate/update, and the corresponding dashboard generate/update/duplicate paths. It also checks that sanitized over-limit values still fail and that successful stripping reports a warning.
- `test_sibling_sanitized_length_budget`: every remaining caller of the shared sanitizer at its final text limit and one character over it.
- `test_sanitized_length_budget`: tag removal, removable Unicode, and entity decoding, through both sanitizer entry points.
- `test_raw_sanitization_input_is_bounded_before_html_parsing`: oversized raw markup is rejected before parsing.
With the original source restored, these tests produced 104 failures and 37 passes; the passing cases are the unchanged over-limit rejection guards. The updated source passes all 141 cases. The byte-string follow-up adds 20 cases that fail on the initial ordering change and pass at the final head. Docker pytest passes both touched modules (1,180 tests) plus the utility/tool/normalization sibling selection (1,144 tests; overlapping utility coverage). The three Bullet/Rose Jest suites pass all 32 tests. Scoped pre-commit passes, including mypy, Ruff and Pylint.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6396 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (shared generate/update chart-name mixin and all four aliases)
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (generate title and aliases)
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (update title and aliases)
- superset/mcp_service/dashboard/schemas.py:1539 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (duplicate title and aliases)
- superset/mcp_service/dashboard/schemas.py:1397 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (certified_by)
- superset/mcp_service/dashboard/schemas.py:1422 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (certification_details)
- superset/mcp_service/chart/schemas.py:883 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (temporal column)
- superset/mcp_service/chart/schemas.py:1009 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (column name)
- superset/mcp_service/chart/schemas.py:1021 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (display label)
- superset/mcp_service/chart/schemas.py:1144 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (filter column)
- superset/mcp_service/chart/schemas.py:1227 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (Gantt sort column)
- superset/mcp_service/chart/schemas.py:2781 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (Sunburst time range)
- superset/mcp_service/chart/schemas.py:3177 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (pivot comparison period)
- superset/mcp_service/chart/schemas.py:4650 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (Bullet range/marker/marker-line labels)
- superset/mcp_service/chart/schemas.py:4664 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (Bullet time range)
- superset/mcp_service/utils/sanitization.py:233 — fixed in 335dbaf204c7684af3e990505949a35c61cee635 (warning wrapper delegates to shared sanitizer)
- superset/mcp_service/chart/tool/generate_chart.py:255 — not affected: revalidation carries over the already-sanitized name; no raw-length check there
- superset/mcp_service/chart/validation/pipeline.py:326 — not affected: normalized requests carry over the already-sanitized name
- superset/mcp_service/dataset/schemas.py — not affected: names are not HTML-stripped; markup is literal and counts toward storage length
- superset/mcp_service/sql_lab/schemas.py — not affected: labels and tab titles are not HTML-stripped
- superset/mcp_service/theme/schemas.py — not affected: theme names are not HTML-stripped
- superset/mcp_service/utils/sanitization.py:365 — not affected: chart-name cap does not apply; filter values use a separate sanitizer with their own 1,000-character raw-input contract, not this shared user-text sanitizer
- superset/mcp_service/utils/sanitization.py:467 — not affected: SQL expressions reject HTML tags rather than strip them
- superset/mcp_service/utils/error_builder.py:54 — not affected: separate error-display truncation helper, not schema input sanitization
I searched with `rg -n 'sanitize_user_input|sanitize_filter_value|sanitize_sql_expression' superset/mcp_service --glob '*.py'` and checked the dataset, SQL Lab, and theme name validators too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6320212417
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/45575?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `20.00000%` with `4 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 65.26%. Comparing base ([`cdc9430`](https://app.codecov.io/gh/apache/superset/commit/cdc9430597c84ce1c89b400cf3215247b372d657?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`28f339c`](https://app.codecov.io/gh/apache/superset/commit/28f339c712d82e357db40ec224466755b794784d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/45575?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/mcp\_service/chart/schemas.py](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fchart%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY2hhcnQvc2NoZW1hcy5weQ==) | 0.00% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/dashboard/schemas.py](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdashboard%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGFzaGJvYXJkL3NjaGVtYXMucHk=) | 50.00% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/utils/schema\_utils.py](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&filepath=superset%2Fmcp_service%2Futils%2Fschema_utils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvdXRpbHMvc2NoZW1hX3V0aWxzLnB5) | 0.00% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/45575?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #45575 +/- ##
==========================================
- Coverage 65.49% 65.26% -0.23%
==========================================
Files 3056 3056
Lines 201163 201157 -6
Branches 47040 47040
==========================================
- Hits 131756 131290 -466
- Misses 66454 66911 +457
- Partials 2953 2956 +3
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.91% <20.00%> (+<0.01%)` | :arrow_up: |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [presto](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `36.64% <20.00%> (+<0.01%)` | :arrow_up: |
| [python](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `52.73% <20.00%> (-0.41%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/45575/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `52.62% <20.00%> (+<0.01%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/45575?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6320350234
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 28f339c712d82e357db40ec224466755b794784d |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6ad8e008b6e24308e1ea07c3 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-45575--superset-docs-preview.netlify.app](https://deploy-preview-45575--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DcpLCoAgEADQu8y6Acsw6QYdw89Egj9GF0V099y9xXuhckm1ww4wgWWT3TV8hhuTq9hDj4TEXBiZTCu5jeapxvIcfkRlvCYhtFW0rFJomsmIzUn4fg) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-45575--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4356250833
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6377,15 +6367,18 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
return data
with field_validation_error("chart_name"):
sanitized, was_modified = sanitize_user_input_with_changes(
- raw, "Chart name", max_length=255, allow_empty=True
+ raw, "Chart name", max_length=250, allow_empty=True
Review Comment:
The 250 cap is now applied by `sanitize_user_input` to the raw string, before tags are stripped. A name like `"<b>" + "x" * 245 + "</b>"` (252 raw chars) is rejected with `string_too_long`, while it would sanitize to a valid 245-character name and was accepted under the old 255 cap. `generate_chart` and `update_chart` both go through this. Is it intended that markup counts toward the name limit, or should the raw-input bound stay looser and the 250 check run on the sanitized value?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4350925836
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,29 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # HTML tag-open states require an ASCII letter, slash, bang or question
+ # mark. Preserve literal comparisons like <30 and <$1M, but never decode
+ # a tag opener reconstructed by stripping intervening markup.
+ # Normalize removable characters before deciding whether a bracket is safe;
+ # otherwise a later Unicode strip could turn <\u200bscript into markup.
+ cleaned = _remove_dangerous_unicode(cleaned)
+ return re.sub(r"<(?![A-Za-z/!?])", "<", cleaned).replace("&", "&")
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce. I restore `>` and NBSP after tag stripping, preserving literal text and length caps without entity-semicolon filter rejections. The allowlist can intentionally leave other brackets escaped, so I also enforce the sanitized storage limit for generate/duplicate dashboard paths without Field caps.
Regressions: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_title_length_counts_plain_text`, `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_filter_value_preserves_greater_than_and_nbsp`, and `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_sibling_fields_preserve_literal_comparison` fail with the reviewed sanitizer and pass with this change. The reviewed-head sanitizer run produced 55 failed / 776 passed. The four `test_*_literal_less_than_storage_round_trip` tool tests gained `>`/NBSP cases: 8 failed / 12 passed against reviewed source, all pass after. The seven touched Python files pass in Docker: 1,232 passed (fastmcp 3.4.7 / nh3 0.3.7 / pydantic 2.14.1; manual/llm_compliance deselected).
Siblings checked:
- superset/mcp_service/chart/schemas.py:6369 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate/save=false/update chart names).
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate titles).
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (update titles).
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (duplicate titles).
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certified_by).
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certification_details).
- superset/mcp_service/chart/schemas.py:879 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (temporal columns).
- superset/mcp_service/chart/schemas.py:1003 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column names).
- superset/mcp_service/chart/schemas.py:1011 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column labels).
- superset/mcp_service/chart/schemas.py:1132 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (filter columns).
- superset/mcp_service/chart/schemas.py:1143 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (scalar/list filter values).
- superset/mcp_service/chart/schemas.py:1211 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Gantt columns).
- superset/mcp_service/chart/schemas.py:2761 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Sunburst ranges).
- superset/mcp_service/chart/schemas.py:3155 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (pivot comparison periods).
- superset/mcp_service/chart/schemas.py:4628 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet range/marker/marker-line labels).
- superset/mcp_service/chart/schemas.py:4637 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet ranges).
- superset/mcp_service/chart/tool/generate_chart.py:255 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression; schema revalidation carries the sanitized title).
- superset/mcp_service/chart/tool/update_chart.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/generate_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/update_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/chart/schemas.py:6435 — not affected: Explore links and update_chart_preview have no title field; their config uses the shared field validators above.
- superset/mcp_service/dataset/schemas.py — not affected: object names/descriptions do not use this HTML sanitizer; literal-text controls remain covered.
- superset/mcp_service/theme/schemas.py — not affected: blank/length validation without HTML stripping.
- superset/mcp_service/sql_lab/schemas.py — not affected: label/tab trimming without HTML stripping.
- superset/mcp_service/utils/sanitization.py:sanitize_sql_expression — not affected: separate SQL canonicalization, with existing comparison-operator tests.
- superset/mcp_service/utils/error_builder.py:54 — not affected: differently named diagnostic scrubber, not a caller of the shared sanitizer.
- superset/charts/schemas.py — not affected: REST does not call the MCP sanitizer; the tooltip rendering changes also cover raw text originating in REST/Explore.
##########
tests/unit_tests/mcp_service/utils/test_sanitization.py:
##########
@@ -903,3 +904,95 @@ def test_data_label_followed_by_control_whitespace_is_preserved(
"""Whitespace after a comma-free data: label may be a tab or line break."""
value = f"Substitute data:{separator}Jira support tickets"
assert sanitize(value) == value.replace("\r\n", "\n")
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "5 < 10",
+ "A < B",
+ "A <",
+ "A <> B",
+ ],
+)
+def test_strip_html_tags_preserves_non_tag_less_than(value: str) -> None:
+ """Preserve display text without decoding tag-opening brackets."""
+ assert _strip_html_tags(value) == value.replace(">", ">")
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce. `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_strip_html_tags_preserves_non_tag_less_than` asserts exact equality, including `A <> B`, `Users aged >30`, and NBSP comparisons. Those assertions fail with the reviewed sanitizer and pass after restoring the safe characters. The full touched Python selection passes in Docker (1,232 passed); filter, schema boundary, warning, resubmission and persistence assertions cover the same behavior rather than preserving the old asymmetry.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6369 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate/save=false/update chart names).
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate titles).
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (update titles).
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (duplicate titles).
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certified_by).
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certification_details).
- superset/mcp_service/chart/schemas.py:879 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (temporal columns).
- superset/mcp_service/chart/schemas.py:1003 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column names).
- superset/mcp_service/chart/schemas.py:1011 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column labels).
- superset/mcp_service/chart/schemas.py:1132 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (filter columns).
- superset/mcp_service/chart/schemas.py:1143 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (scalar/list filter values).
- superset/mcp_service/chart/schemas.py:1211 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Gantt columns).
- superset/mcp_service/chart/schemas.py:2761 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Sunburst ranges).
- superset/mcp_service/chart/schemas.py:3155 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (pivot comparison periods).
- superset/mcp_service/chart/schemas.py:4628 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet range/marker/marker-line labels).
- superset/mcp_service/chart/schemas.py:4637 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet ranges).
- superset/mcp_service/chart/tool/generate_chart.py:255 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression; schema revalidation carries the sanitized title).
- superset/mcp_service/chart/tool/update_chart.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/generate_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/update_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/chart/schemas.py:6435 — not affected: Explore links and update_chart_preview have no title field; their config uses the shared field validators above.
- superset/mcp_service/dataset/schemas.py — not affected: object names/descriptions do not use this HTML sanitizer; literal-text controls remain covered.
- superset/mcp_service/theme/schemas.py — not affected: blank/length validation without HTML stripping.
- superset/mcp_service/sql_lab/schemas.py — not affected: label/tab trimming without HTML stripping.
- superset/mcp_service/utils/sanitization.py:sanitize_sql_expression — not affected: separate SQL canonicalization, with existing comparison-operator tests.
- superset/mcp_service/utils/error_builder.py:54 — not affected: differently named diagnostic scrubber, not a caller of the shared sanitizer.
- superset/charts/schemas.py — not affected: REST does not call the MCP sanitizer; the tooltip rendering changes also cover raw text originating in REST/Explore.
##########
docs/developer_docs/extensions/mcp.md:
##########
@@ -28,6 +28,17 @@ under the License.
Model Context Protocol (MCP) integration allows extensions to register custom AI agent capabilities that integrate seamlessly with Superset's MCP service. Extensions can provide both **tools** (executable functions) and **prompts** (interactive guidance) that AI agents can discover and use.
+## Chart and dashboard titles
+
+MCP chart names and dashboard titles preserve literal comparisons such as
+`Users aged <30`, `Revenue <$1M`, and `Love <3 charts`. HTML tags are stripped;
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce, including the follow-up in this PR. I HTML-escape plain-text fragments using the existing ECharts helper instead of treating labels as rich HTML. I also found the same core-filter use in Rose's drilled pie and changed it.
Regression tests: `superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts::escapes literal comparison text in every Bullet tooltip`, `superset-frontend/plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts::escapes literal series text in Rose tooltips (rich=%s)`, and `superset-frontend/plugins/plugin-chart-echarts/test/Rose/EchartsRose.test.tsx::drilled Rose tooltips preserve literal series and period text`. The three suites produce 5 failed / 27 passed with reviewed source, then 32 passed after the change. They inspect rendered DOM text and ensure label markup stays inert while intended tooltip formatting survives. I used the checkout's core source through a Jest mapper with cached dependencies. The rendering fix covers all input entry points, including Explore.
Siblings checked:
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:229 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (group prefix, metric, containing-range label and formatted value).
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:261 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (range threshold tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:278 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (marker tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:136 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (rich series tooltip, period text and formatted value).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:183 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (plain series tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/EchartsRose.tsx:81 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (drill-down pie tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts:1043 — not affected: this similarly named sanitizeHtml already HTML-escapes with ECharts encodeHTML; reused for these fixes.
- superset-frontend/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts:149 — not affected: both tooltip paths import the escaping helper from utils/series, not the core HTML filter.
- superset-frontend/plugins/plugin-chart-echarts/src/Graph/transformProps.ts:390 — not affected: source/target labels already use the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts:75 — not affected: raw names already use the escaping helper before tooltipHtml.
- superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts:73 — not affected: raw names already use the escaping helper before tooltipHtml.
- superset-frontend/plugins/plugin-chart-echarts/src/Radar/utils.ts:67 — not affected: label/value fragments import the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/forecast.ts:124 — not affected: series labels import the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/eChartOptionsSchema.ts:71 — not affected: sanitizes explicitly HTML-valued option strings, not the plain-text label fragments changed here.
- superset-frontend/packages/superset-ui-core/src/utils/tooltip.ts:78 — not affected: intentionally accepts rich HTML; the Pie/Funnel/Graph callers above escape plain text before calling it.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts — not affected: canvas axis/legend/mark-line labels are not HTML sinks; the common transformer covers MCP, REST and Explore inputs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4366856269
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -6396,16 +6416,24 @@ def _detect_chart_name_sanitization(cls, data: Any) -> Any:
@field_validator("chart_name")
@classmethod
- def sanitize_chart_name(cls, v: str | None) -> str | None:
- """Sanitize chart name to prevent XSS attacks."""
- try:
- return sanitize_user_input(
- v, "Chart name", max_length=255, allow_empty=True
- )
- except ValueError as ex:
- raise PydanticCustomError(
- "unsafe_text", "{error}", {"error": str(ex)}
- ) from ex
+ def normalize_blank_chart_name(cls, v: str | None) -> str | None:
+ """Keep the optional-name fallback; nonblank names are sanitized above."""
+ return v if v and v.strip() else None
Review Comment:
Yes. Fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d: blank chart names normalize to None before the field length constraint, including chart_name/name/title/slice_name aliases. Dashboard creation preserves its explicit-empty-string behavior; whitespace-only titles fall back before length validation. Required update/duplicate dashboard titles report empty_text instead of a length error for long blanks.
Regression test: tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_blank_titles_normalize_before_length. Against the reviewed source at 619fb05753d733106d99cce0dfb8a41eb7165d48, 132 cases fail; they pass with the change. Coverage includes string/bytes/bytearray inputs, every alias, and blanks of length 251, 501, and 10001. Empty-string cases retain the established semantics.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6429 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/chart/schemas.py:6484 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:781 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:926 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:1487 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:506 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:578 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/sql_lab/schemas.py:233 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/sql_lab/schemas.py:301 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:699 — not affected: metric names retain literal whitespace and have no optional blank-name fallback or HTML sanitizer; Pydantic decodes bytes before the existing after-validator rejects blank names.
- superset/mcp_service/dataset/schemas.py:1010 — not affected: update table names retain literal whitespace and have no optional blank-name fallback or HTML sanitizer; the after-validator checks decoded names.
- superset/mcp_service/theme/schemas.py:138 — not affected: theme names intentionally retain and count whitespace, and their after-validator checks decoded strings.
- superset/mcp_service/chart/schemas.py:6467 — not affected: generate_explore_link has no chart-name field.
- superset/mcp_service/chart/schemas.py:6574 — not affected: update_chart_preview has no chart-name field.
- superset/mcp_service/dataset/schemas.py:879 — not affected: slice_name here is response metadata, not a title-writing request.
Validation: Docker pytest selected regressions: 436 passed (228 failed / 208 passed with reviewed schemas). Related Python suites: 3012 passed and 1846 passed. Changed-file pre-commit passed.
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,789 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_escaped_title_still_fits_model_column(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Conservative bracket escaping cannot bypass a persisted title's length cap."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2) + "<ſ"
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("whitespace", ["\t", "\n", "\r", "\v", "\f", "\x85"])
+@pytest.mark.parametrize(
+ "control",
+ ["!channel", "@U123", "#C123|general", "https://example.invalid|Open dashboard"],
+)
+def test_title_control_whitespace_cannot_form_slack_markup(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ whitespace: str,
+ control: str,
+) -> None:
+ """Report title normalization must not join brackets into Slack controls."""
+ from superset.utils.file import sanitize_title
+
+ value = f"Q3 <{whitespace}{control}>"
+ request = model.model_validate({**payload, field: value})
+ stored = getattr(request, field)
+ assert "<" not in sanitize_title(stored)
+ assert getattr(model.model_validate(request.model_dump()), field) == stored
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("alias_index", range(4))
+@pytest.mark.parametrize("length_delta", [-5, 0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_markup_title_length_uses_sanitized_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ alias_index: int,
+ length_delta: int,
+ padding: str,
+) -> None:
+ """Markup is not part of the persisted title's character budget."""
+ aliases = (
+ ("chart_name", "name", "title", "slice_name")
+ if field == "chart_name"
+ else ("dashboard_title", "title", "name", "dashboard_title")
+ )
+ limit = 250 if field == "chart_name" else 500
+ text = "x" * (limit + length_delta)
+ value = "<b>" + padding + text + padding + "</b>"
+ if length_delta > 0:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, aliases[alias_index]: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate({**payload, aliases[alias_index]: value})
+ assert getattr(request, field) == text
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [case for case in _SIBLING_SANITIZATION_CASES if case[2] != "value"],
+)
+@pytest.mark.parametrize("extra", [0, 1])
+@pytest.mark.parametrize("padding", ["", " ", " ", "\u00a0"])
+def test_sibling_sanitized_length_budget(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ extra: int,
+ padding: str,
+) -> None:
+ """All callers of the shared text sanitizer enforce the final text cap."""
+ limits = {
+ "certified_by": 500,
+ "certification_details": 5000,
+ "temporal_column": 255,
+ "name": 255,
+ "label": 500,
+ "column": 255,
+ "time_range": 1000,
+ "comparison_period": 100,
+ "range_labels": 200,
+ "marker_labels": 200,
+ "marker_line_labels": 200,
+ }
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ text = "x" * (limits[field] + extra)
+ value = "<b>" + padding + text + padding + "</b>"
+ if extra:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ else:
+ request = model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert getattr(request, field) == (
+ [text] if field.endswith("_labels") else text
+ )
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ case
+ for case in _SIBLING_SANITIZATION_CASES
+ if case[2] != "value" and not case[2].endswith("_labels")
+ ],
+)
+@pytest.mark.parametrize("value", [b"<b>Safe</b>", bytearray(b"<b>Safe</b>")])
Review Comment:
Fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d: chart and dashboard title guards decode UTF-8 bytes/bytearray before sanitization and length validation, preserving stripped-only rejection and server-only warnings. I expanded the existing byte-input parametrization to all chart/dashboard name models and added alias/length-boundary cases. The related dashboard-slug coercion regression is covered in 746c57391cecb0fba4771a678914bfa1131efd73.
Regression tests in tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
- test_sibling_byte_strings_are_sanitized_before_coercion — the 12 added title-model cases fail with reviewed source and pass after.
- test_byte_title_sanitized_length_boundary — 64 cases fail before and pass after; over-limit rejection controls remain passing.
- test_byte_title_removed_content_is_rejected — 12 cases fail before and pass after.
- test_byte_object_name_trims_before_length — all 8 sibling-name cases fail before and pass after.
- test_byte_dashboard_slug_normalizes_before_length — all 6 cases fail before the slug change and pass after.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6429 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/chart/schemas.py:6484 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:781 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:926 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dashboard/schemas.py:1487 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:506 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:578 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/sql_lab/schemas.py:233 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/sql_lab/schemas.py:301 — fixed in e0145e7cd6befa328b77b7a7aaa96a9784728e9d
- superset/mcp_service/dataset/schemas.py:699 — not affected: metric names retain literal whitespace and have no optional blank-name fallback or HTML sanitizer; Pydantic decodes bytes before the existing after-validator rejects blank names.
- superset/mcp_service/dataset/schemas.py:794 — not affected: update_dataset_metric inherits the literal metric-name after-validator.
- superset/mcp_service/dataset/schemas.py:805 — not affected: create_dataset_metric inherits the literal metric-name after-validator.
- superset/mcp_service/dataset/schemas.py:1010 — not affected: update table names retain literal whitespace and have no optional blank-name fallback or HTML sanitizer; the after-validator checks decoded names.
- superset/mcp_service/theme/schemas.py:138 — not affected: theme names intentionally retain and count whitespace, and their after-validator checks decoded strings.
- superset/mcp_service/chart/schemas.py:6467 — not affected: generate_explore_link has no chart-name field.
- superset/mcp_service/chart/schemas.py:6574 — not affected: update_chart_preview has no chart-name field.
- superset/mcp_service/dataset/schemas.py:879 — not affected: slice_name here is response metadata, not a title-writing request.
- superset/mcp_service/dashboard/schemas.py:1095 — fixed in 746c57391cecb0fba4771a678914bfa1131efd73
- superset/mcp_service/chart/schemas.py:877 — not affected: temporal_column already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:1003 — not affected: ColumnRef.name already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:1015 — not affected: ColumnRef.label already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:1138 — not affected: FilterConfig.column already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:1150 — not affected: filter values sanitize after Pydantic coercion.
- superset/mcp_service/chart/schemas.py:1221 — not affected: GanttSortByConfig.column already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:2775 — not affected: Sunburst time_range already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:3171 — not affected: pivot comparison_period already decodes bytes before sanitization.
- superset/mcp_service/chart/schemas.py:4637 — not affected: Bullet label lists sanitize after their string elements are coerced.
- superset/mcp_service/chart/schemas.py:4657 — not affected: Bullet time_range already decodes bytes before sanitization.
- superset/mcp_service/dashboard/schemas.py:1401 — not affected: certification text already decodes bytes before sanitization.
- superset/mcp_service/dashboard/schemas.py:1425 — not affected: certification details already decode bytes before sanitization.
Validation: reviewed schemas produce 228 failures / 208 passes for the 436 selected cases; the changed schemas pass all 436. The separate slug regression produced 6 failures before its change. Changed-file pre-commit passed; touched Jest suites: 32 passed. Real-LLM checks were excluded.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4350928022
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,29 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # HTML tag-open states require an ASCII letter, slash, bang or question
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce. I adopted the comparison-character allowlist. `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_strip_html_tags_keeps_casefolding_tag_openers_escaped` fails for both U+017F and U+212A with reviewed source and passes after the change; `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_strip_html_tags_preserves_non_tag_less_than` retains the literal-comparison contract. `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_escaped_title_still_fits_model_column` additionally caught generate/duplicate dashboard overflow from intentionally retained escaping (2 failed before the storage-cap guard, all pass after). Docker: 1,232 touched Python tests passed. The tooltip sibling fix escapes the corresponding display fragments.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6369 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate/save=false/update chart names).
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate titles).
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (update titles).
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (duplicate titles).
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certified_by).
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certification_details).
- superset/mcp_service/chart/schemas.py:879 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (temporal columns).
- superset/mcp_service/chart/schemas.py:1003 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column names).
- superset/mcp_service/chart/schemas.py:1011 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column labels).
- superset/mcp_service/chart/schemas.py:1132 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (filter columns).
- superset/mcp_service/chart/schemas.py:1143 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (scalar/list filter values).
- superset/mcp_service/chart/schemas.py:1211 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Gantt columns).
- superset/mcp_service/chart/schemas.py:2761 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Sunburst ranges).
- superset/mcp_service/chart/schemas.py:3155 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (pivot comparison periods).
- superset/mcp_service/chart/schemas.py:4628 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet range/marker/marker-line labels).
- superset/mcp_service/chart/schemas.py:4637 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet ranges).
- superset/mcp_service/chart/tool/generate_chart.py:255 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression; schema revalidation carries the sanitized title).
- superset/mcp_service/chart/tool/update_chart.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/generate_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/update_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/chart/schemas.py:6435 — not affected: Explore links and update_chart_preview have no title field; their config uses the shared field validators above.
- superset/mcp_service/dataset/schemas.py — not affected: object names/descriptions do not use this HTML sanitizer; literal-text controls remain covered.
- superset/mcp_service/theme/schemas.py — not affected: blank/length validation without HTML stripping.
- superset/mcp_service/sql_lab/schemas.py — not affected: label/tab trimming without HTML stripping.
- superset/mcp_service/utils/sanitization.py:sanitize_sql_expression — not affected: separate SQL canonicalization, with existing comparison-operator tests.
- superset/mcp_service/utils/error_builder.py:54 — not affected: differently named diagnostic scrubber, not a caller of the shared sanitizer.
- superset/charts/schemas.py — not affected: REST does not call the MCP sanitizer; the tooltip rendering changes also cover raw text originating in REST/Explore.
Siblings checked:
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:229 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (group prefix, metric, containing-range label and formatted value).
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:261 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (range threshold tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:278 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (marker tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:136 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (rich series tooltip, period text and formatted value).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:183 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (plain series tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/EchartsRose.tsx:81 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (drill-down pie tooltip).
- superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts:1043 — not affected: this similarly named sanitizeHtml already HTML-escapes with ECharts encodeHTML; reused for these fixes.
- superset-frontend/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts:149 — not affected: both tooltip paths import the escaping helper from utils/series, not the core HTML filter.
- superset-frontend/plugins/plugin-chart-echarts/src/Graph/transformProps.ts:390 — not affected: source/target labels already use the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts:75 — not affected: raw names already use the escaping helper before tooltipHtml.
- superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts:73 — not affected: raw names already use the escaping helper before tooltipHtml.
- superset-frontend/plugins/plugin-chart-echarts/src/Radar/utils.ts:67 — not affected: label/value fragments import the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/forecast.ts:124 — not affected: series labels import the escaping helper.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/eChartOptionsSchema.ts:71 — not affected: sanitizes explicitly HTML-valued option strings, not the plain-text label fragments changed here.
- superset-frontend/packages/superset-ui-core/src/utils/tooltip.ts:78 — not affected: intentionally accepts rich HTML; the Pie/Funnel/Graph callers above escape plain text before calling it.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts — not affected: canvas axis/legend/mark-line labels are not HTML sinks; the common transformer covers MCP, REST and Explore inputs.
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1065,17 +1069,17 @@ def _detect_dashboard_title_sanitization(cls, data: Any) -> Any:
@field_validator("dashboard_title")
@classmethod
- def sanitize_dashboard_title(cls, v: str | None) -> str | None:
- """Sanitize dashboard title to prevent XSS."""
- if v is None or v == "":
+ def normalize_blank_dashboard_title(cls, v: str | None) -> str | None:
+ """Reject blank updates; nonblank titles are sanitized above."""
+ if v is None:
return v
- return sanitize_user_input(
- v, "Dashboard title", max_length=500, allow_empty=True
- )
+ if not v.strip():
+ raise PydanticCustomError("empty_text", "dashboard_title cannot be empty")
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce. I added the `## Next` migration note covering explicit blank dashboard renames, omission to retain the stored title, chart names dropping from the published 255 limit to 250, and the new 250-character theme-name cap.
Regression: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_name_contract_changes_have_upgrade_guidance` fails with the reviewed UPDATING.md and passes after this change (the two documentation tests failed before, both pass in the 1,232-test Docker run). Runtime contracts remain pinned by `test_update_dashboard_blank_title_wire_reason`, `test_chart_name_model_column_boundary`, and `test_theme_name_model_column_boundary` in the same PR test file.
Siblings checked:
- UPDATING.md:28 — fixed in 6143776c9a761201f4633bcf804243f5901094ce.
- docs/admin_docs/configuration/mcp-server.mdx:2428 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (blank rename and all name/length guidance together).
- docs/developer_docs/extensions/mcp.md — fixed in 6143776c9a761201f4633bcf804243f5901094ce (built-in validation text moved to administration).
- superset/mcp_service/chart/schemas.py:6330 — not affected: existing runtime 250 cap is documented, not changed again.
- superset/mcp_service/dashboard/schemas.py:1072 — not affected: existing explicit-blank rejection is documented.
- superset/mcp_service/theme/schemas.py:143 — not affected: existing 250 cap is documented.
##########
docs/developer_docs/extensions/mcp.md:
##########
@@ -587,3 +598,17 @@ governance concern from layout/theme/metadata edits.
- **[Development](./development.md)** - Project structure, APIs, and dev workflow
- **[Security](./security.md)** - Security best practices for extensions
+
+## Object-name validation
Review Comment:
Fixed in 6143776c9a761201f4633bcf804243f5901094ce. I moved both “Chart and dashboard titles” and “Object-name validation” to the admin MCP server documentation, retaining theme/saved-query/SQL Lab/slug caps, trim-before-length and the theme whitespace exception. Neither section remains after “Next Steps” on the extension page.
Regression: `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_builtin_name_validation_documented_for_administrators` fails with reviewed documentation and passes after the move (both documentation regressions pass in the 1,232-test Docker run).
Siblings checked:
- docs/developer_docs/extensions/mcp.md — fixed in 6143776c9a761201f4633bcf804243f5901094ce (both built-in validation sections removed).
- docs/admin_docs/configuration/mcp-server.mdx:2428 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (title-error guidance retained).
- docs/admin_docs/configuration/mcp-server.mdx:2447 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (literal title handling moved here).
- docs/admin_docs/configuration/mcp-server.mdx:2458 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (object caps and trimming moved here).
- docs/developer_docs/extensions/mcp.md:31 — not affected: pre-existing chart-dataset rebinding guidance is outside these two validation sections and unchanged.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #45575:
URL: https://github.com/apache/superset/pull/45575#issuecomment-6345936163
@rebenitez1802 I fixed the review-body ask in 6143776c9a761201f4633bcf804243f5901094ce: `>` and NBSP retain their literal text, and valid title lengths are not inflated by escaping. `tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py::test_title_length_counts_plain_text` and `tests/unit_tests/mcp_service/utils/test_sanitization.py::test_filter_value_preserves_greater_than_and_nbsp` fail against the reviewed sanitizer and pass after; the four tool storage/readback tests additionally reproduce 8 failures before and pass after. The full seven-file Docker selection passes: 1,232 tests, using fastmcp 3.4.7 / nh3 0.3.7 / pydantic 2.14.1, with manual/llm_compliance deselected. Each of the six inline asks has its own evidence reply, including the Bullet/Rose follow-up, allowlist hardening, migration note and documentation move.
Validation limitation: branch-scoped pre-commit ran; Python checks, frontend lint and formatting passed, but frontend type checking reports missing built declaration outputs (TS6305) and stylelint cannot resolve postcss-styled-syntax in this checkout. Real-LLM checks not run: OpenRouter disabled.
Siblings checked:
- superset/mcp_service/chart/schemas.py:6369 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate/save=false/update chart names).
- superset/mcp_service/dashboard/schemas.py:884 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (generate titles).
- superset/mcp_service/dashboard/schemas.py:1050 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (update titles).
- superset/mcp_service/dashboard/schemas.py:1531 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (duplicate titles).
- superset/mcp_service/dashboard/schemas.py:1393 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certified_by).
- superset/mcp_service/dashboard/schemas.py:1414 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (certification_details).
- superset/mcp_service/chart/schemas.py:879 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (temporal columns).
- superset/mcp_service/chart/schemas.py:1003 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column names).
- superset/mcp_service/chart/schemas.py:1011 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (column labels).
- superset/mcp_service/chart/schemas.py:1132 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (filter columns).
- superset/mcp_service/chart/schemas.py:1143 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (scalar/list filter values).
- superset/mcp_service/chart/schemas.py:1211 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Gantt columns).
- superset/mcp_service/chart/schemas.py:2761 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Sunburst ranges).
- superset/mcp_service/chart/schemas.py:3155 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (pivot comparison periods).
- superset/mcp_service/chart/schemas.py:4628 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet range/marker/marker-line labels).
- superset/mcp_service/chart/schemas.py:4637 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (Bullet ranges).
- superset/mcp_service/chart/tool/generate_chart.py:255 — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression; schema revalidation carries the sanitized title).
- superset/mcp_service/chart/tool/update_chart.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/generate_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/dashboard/tool/update_dashboard.py — fixed in 6143776c9a761201f4633bcf804243f5901094ce (storage/readback regression).
- superset/mcp_service/chart/schemas.py:6435 — not affected: Explore links and update_chart_preview have no title field; their config uses the shared field validators above.
- superset/mcp_service/dataset/schemas.py — not affected: object names/descriptions do not use this HTML sanitizer; literal-text controls remain covered.
- superset/mcp_service/theme/schemas.py — not affected: blank/length validation without HTML stripping.
- superset/mcp_service/sql_lab/schemas.py — not affected: label/tab trimming without HTML stripping.
- superset/mcp_service/utils/sanitization.py:sanitize_sql_expression — not affected: separate SQL canonicalization, with existing comparison-operator tests.
- superset/mcp_service/utils/error_builder.py:54 — not affected: differently named diagnostic scrubber, not a caller of the shared sanitizer.
- superset/charts/schemas.py — not affected: REST does not call the MCP sanitizer; the tooltip rendering changes also cover raw text originating in REST/Explore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "rebenitez1802 (via GitHub)" <gi...@apache.org>.
rebenitez1802 commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4352609612
##########
tests/unit_tests/mcp_service/test_sanitization_warning_inputs.py:
##########
@@ -524,3 +579,683 @@ def validate(request: BaseModel) -> str:
)
assert f"request.{field}: Contains disallowed content" in message
assert "private-input" not in message
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "limit"),
+ [
+ ("generate_dashboard", {"chart_ids": [1]}, "dashboard_title", 500),
+ ("update_dashboard", {"identifier": 1}, "dashboard_title", 500),
+ ("duplicate_dashboard", {"dashboard_id": 1}, "dashboard_title", 500),
+ (
+ "generate_chart",
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ 250,
+ ),
+ ("update_chart", {"identifier": 1}, "chart_name", 250),
+ ],
+)
+@pytest.mark.parametrize("alias", [None, "title", "name"])
+@pytest.mark.parametrize("length", [None, 600])
+async def test_title_length_wire_reason(
+ tool: str,
+ payload: dict[str, Any],
+ field: str,
+ limit: int,
+ alias: str | None,
+ length: int | None,
+) -> None:
+ """Length errors retain their reason through warning detection and MCP."""
+ rejected = "x" * (length or limit + 1)
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, alias or field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "String exceeds the allowed maximum length",
+ )
+ ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("rejected", ["", " \t\n"])
+async def test_duplicate_dashboard_empty_title_wire_reason(
+ field: str,
+ rejected: str,
+) -> None:
+ """Blank required titles have a static, actionable reason on the wire."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Text must not be empty",
+ )
+ ]
+
+
+_REQUIRED_NAME_CASES: list[tuple[str, dict[str, Any], str, list[str | None]]] = [
+ (
+ "create_virtual_dataset",
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ["", " \t\n"],
+ ),
+ ("create_theme", {"json_data": {}}, "theme_name", ["", " \t\n"]),
+ (
+ "create_dataset_metric",
+ {"dataset_id": 1, "expression": "count(*)"},
+ "metric_name",
+ ["", " \t\n"],
+ ),
+ (
+ "update_dataset_metric",
+ {"dataset_id": 1, "metric": 1},
+ "metric_name",
+ ["", " \t\n", None],
+ ),
+ ("update_dataset", {"dataset_id": 1}, "table_name", ["", " \t\n", None]),
+ (
+ "save_sql_query",
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ["", " \t\n"],
+ ),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("tool", "payload", "field", "rejected"),
+ [
+ (tool, payload, field, rejected)
+ for tool, payload, field, blanks in _REQUIRED_NAME_CASES
+ for rejected in blanks
+ ],
+)
+async def test_required_name_empty_wire_reason(
+ tool: str, payload: dict[str, Any], field: str, rejected: str | None
+) -> None:
+ """Blank object names report a safe reason at the declared field."""
+ async with Client(make_name_server()) as client:
+ result = await client.call_tool_mcp(
+ tool, {"request": {**payload, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text=f"Error: Validation error in {tool}: request.{field}: "
+ "Text must not be empty",
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("length", [250, 251, 252, 253, 254, 255])
+def test_chart_name_model_column_boundary(
+ model: type[BaseModel], payload: dict[str, Any], length: int
+) -> None:
+ """Chart names must fit the persisted Slice name column."""
+ from superset.models.slice import Slice
+
+ limit = Slice.__table__.c.slice_name.type.length
+ assert limit == 250
+ if length <= limit:
+ assert (
+ model.model_validate({**payload, "chart_name": "x" * length}).chart_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, "chart_name": "x" * length})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ ),
+ (UpdateChartRequest, {"identifier": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("length", [250, 251])
+def test_padded_chart_name_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Validate the trimmed chart name against the model column boundary."""
+ value = " " + "x" * length + " "
+ if length == 250:
+ assert (
+ model.model_validate({**payload, alias: value}).chart_name == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize("length", [250, 251, 310])
+def test_theme_name_model_column_boundary(length: int) -> None:
+ """Theme creation must respect its persisted name column."""
+ from superset.models.core import Theme
+
+ assert Theme.__table__.c.theme_name.type.length == 250
+ if length == 250:
+ assert (
+ CreateThemeRequest(theme_name="x" * length, json_data={}).theme_name
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ CreateThemeRequest(theme_name="x" * length, json_data={})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("value", ["", " \t\n"])
+async def test_update_dashboard_blank_title_wire_reason(alias: str, value: str) -> None:
+ """Reject blank renames rather than reporting a title that was not saved."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "update_dashboard", {"request": {"identifier": 1, alias: value}}
+ )
+ assert result.isError is True
+ assert "request.dashboard_title: Text must not be empty" in result.content[0].text
+
+
+@pytest.mark.parametrize("alias", ["chart_name", "name", "title", "slice_name"])
+@pytest.mark.parametrize("script_only", [True, False])
+def test_update_chart_sanitization_matches_generate(
+ alias: str, script_only: bool
+) -> None:
+ """Update rejects stripped-only names and warns on partially stripped names."""
+ if script_only:
+ with pytest.raises(ValidationError) as exc:
+ UpdateChartRequest.model_validate(
+ {"identifier": 1, alias: "<script>alert(1)</script>"}
+ )
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+ assert exc.value.errors()[0]["loc"] == ("chart_name",)
+ return
+ request = UpdateChartRequest.model_validate(
+ {
+ "identifier": 1,
+ alias: "Weekly KPIs <img src=x onerror=alert(1)>",
+ "sanitization_warnings": ["untrusted"],
+ }
+ )
+ assert request.chart_name == "Weekly KPIs"
+ assert len(request.sanitization_warnings) == 1
+ assert "untrusted" not in request.sanitization_warnings
+ assert "sanitization_warnings" not in json.dumps(
+ UpdateChartRequest.model_json_schema()
+ )
+
+
+def test_duplicate_dataset_error_is_readable() -> None:
+ """Duplicate errors use a plain string and preserve display-name characters."""
+ from superset.commands.dataset.exceptions import DatasetExistsValidationError
+ from superset.sql.parse import Table
+
+ name = "Sales “Q3” & Growth"
+ error = DatasetExistsValidationError(
+ Table(name, schema="my schema", catalog="my catalog")
+ )
+ assert error.normalized_messages() == {
+ "table": [f"Dataset my catalog.my schema.{name} already exists"]
+ }
+ assert type(error.messages[0]) is str
+
+
+@pytest.mark.parametrize(
+ "kind,limit", [("dataset", 250), ("saved_query", 256), ("tab", 256)]
+)
+@pytest.mark.parametrize("extra", [0, 1])
+def test_padded_sibling_name_boundary(kind: str, limit: int, extra: int) -> None:
+ """Persisted names that trim must check the length after trimming."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ cases: dict[str, tuple[type[BaseModel], dict[str, Any], str]] = {
+ "dataset": (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ "saved_query": (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "label",
+ ),
+ "tab": (OpenSqlLabRequest, {"database_id": 1}, "title"),
+ }
+ model, payload, field = cases[kind]
+ value = "x" * (limit + extra)
+ if not extra:
+ assert (
+ getattr(model.model_validate({**payload, field: f" {value} "}), field)
+ == value
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: f" {value} "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+@pytest.mark.parametrize(
+ "model,payload",
+ [
+ (GenerateDashboardRequest, {"chart_ids": [1]}),
+ (UpdateDashboardRequest, {"identifier": 1}),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}),
+ ],
+)
+@pytest.mark.parametrize("alias", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize("length", [500, 501])
+def test_padded_dashboard_title_boundary(
+ model: type[BaseModel], payload: dict[str, Any], alias: str, length: int
+) -> None:
+ """Dashboard aliases check the trimmed title against the column cap."""
+ if length == 500:
+ assert (
+ model.model_validate(
+ {**payload, alias: " " + "x" * length + " "}
+ ).dashboard_title
+ == "x" * length
+ )
+ else:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, alias: " " + "x" * length + " "})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+
+
+def test_padded_dashboard_slug_boundary() -> None:
+ """Update slug normalization precedes its persisted column limit."""
+ request = UpdateDashboardRequest(identifier=1, slug=" " + "x" * 255 + " ")
+ assert request.slug == "x" * 255
+ with pytest.raises(ValidationError):
+ UpdateDashboardRequest(identifier=1, slug=" " + "x" * 256 + " ")
+
+
+_TITLE_SANITIZATION_CASES = [
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ "save_chart": False,
+ },
+ "chart_name",
+ ),
+ (
+ GenerateChartRequest,
+ {
+ "dataset_id": 1,
+ "config": {"chart_type": "table", "columns": [{"name": "a"}]},
+ },
+ "chart_name",
+ ),
+ (UpdateChartRequest, {"identifier": 1}, "chart_name"),
+ (GenerateDashboardRequest, {"chart_ids": [1]}, "dashboard_title"),
+ (UpdateDashboardRequest, {"identifier": 1}, "dashboard_title"),
+ (DuplicateDashboardRequest, {"dashboard_id": 1}, "dashboard_title"),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "Users aged <30 & “VIP” 📈",
+ "Users aged >30",
+ "Revenue\u00a0>\u00a0$1M",
+ ],
+)
+def test_literal_less_than_title_round_trip(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-tag less-than signs survive validation and JSON readback unchanged."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert request.sanitization_warnings == []
+ assert json.loads(request.model_dump_json())[field] == value
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Weekly <img src=x>KPIs", "Q3 <b>revenue</b> & costs"]
+)
+def test_title_sanitized_once(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Persist the single sanitizer result, never a second-pass empty fallback."""
+ from unittest.mock import patch
+
+ from superset.mcp_service.utils.sanitization import sanitize_user_input
+
+ expected = sanitize_user_input(value, "Title", max_length=500, allow_empty=True)
+ assert expected
+ with (
+ patch(
+ "superset.mcp_service.utils.sanitization.sanitize_user_input",
+ wraps=sanitize_user_input,
+ ) as sanitize,
+ patch("superset.mcp_service.chart.schemas.sanitize_user_input", sanitize),
+ patch("superset.mcp_service.dashboard.schemas.sanitize_user_input", sanitize),
+ ):
+ request = model.model_validate({**payload, field: value})
+ calls = [
+ c
+ for c in sanitize.call_args_list
+ if c.args[1] in ("Chart name", "Dashboard title")
+ ]
+ assert len(calls) == 1
+ assert getattr(request, field) == expected
+ assert len(request.sanitization_warnings) == 1
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_reconstructed_tag_title_rejected(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Encoded tag text is rejected instead of stored or auto-named."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+def test_empty_sanitized_title_never_uses_fallback(
+ model: type[BaseModel], payload: dict[str, Any], field: str
+) -> None:
+ """Encoded script-only names retain the existing disallowed-content reason."""
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: "&lt;script>alert(1)</script>"})
+ assert exc.value.errors()[0]["loc"] == (field,)
+ assert exc.value.errors()[0]["type"] == "unsafe_text"
+
+
+_SIBLING_SANITIZATION_CASES = [
+ (ManageDashboardCertificationRequest, {"identifier": 1}, "certified_by"),
+ (
+ ManageDashboardCertificationRequest,
+ {"identifier": 1},
+ "certification_details",
+ ),
+ (BaseChartConfig, {}, "temporal_column"),
+ (ColumnRef, {}, "name"),
+ (ColumnRef, {"name": "amount"}, "label"),
+ (FilterConfig, {"op": "=", "value": "safe"}, "column"),
+ (FilterConfig, {"column": "region", "op": "="}, "value"),
+ (GanttSortByConfig, {}, "column"),
+ (
+ SunburstChartConfig,
+ {
+ "hierarchy": [{"name": "region"}],
+ "metric": {"name": "amount", "aggregate": "SUM"},
+ },
+ "time_range",
+ ),
+ (
+ InteractivePivotChartConfig,
+ {
+ "rows": [{"name": "region"}],
+ "metrics": [{"name": "amount", "aggregate": "SUM"}],
+ },
+ "comparison_period",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "time_range",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "range_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_labels",
+ ),
+ (
+ BulletChartConfig,
+ {"metric": {"name": "amount", "aggregate": "SUM"}},
+ "marker_line_labels",
+ ),
+]
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["Users aged <30", "Users aged >30", "Users\u00a0>30"]
+)
+def test_sibling_fields_preserve_literal_comparison(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Every sibling accepts a non-tag comparison and preserves its literal text."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ expected = [value] if field.endswith("_labels") else value
+ request = model.model_validate({**payload, field: expected})
+ assert getattr(request, field) == expected
+
+
+@pytest.mark.parametrize("model,payload,field", _SIBLING_SANITIZATION_CASES)
+@pytest.mark.parametrize(
+ "value", ["<<</b>x", "&lt;</script>click= <b>📈"]
+)
+def test_sibling_fields_reject_reconstructed_tag(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Reconstructed tag openers fail with a canonical field and typed reason."""
+ if model is InteractivePivotChartConfig:
+ payload = {**payload, "comparison_type": "values"}
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate(
+ {**payload, field: [value] if field.endswith("_labels") else value}
+ )
+ assert [(error["type"], error["loc"]) for error in exc.value.errors()] == [
+ ("unsafe_text", (field,))
+ ]
+
+
+@pytest.mark.parametrize(
+ "model,payload,field",
+ [
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1"},
+ "dataset_name",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "table_name"),
+ (
+ CreateDatasetMetricRequest,
+ {"dataset_id": 1, "expression": "SUM(x)"},
+ "metric_name",
+ ),
+ (UpdateDatasetMetricRequest, {"dataset_id": 1, "metric": 1}, "metric_name"),
+ (CreateThemeRequest, {"json_data": {}}, "theme_name"),
+ (SaveSqlQueryRequest, {"database_id": 1, "sql": "select 1"}, "label"),
+ (
+ CreateVirtualDatasetRequest,
+ {"database_id": 1, "sql": "select 1", "dataset_name": "ds"},
+ "description",
+ ),
+ (UpdateDatasetRequest, {"dataset_id": 1}, "description"),
+ (
+ SaveSqlQueryRequest,
+ {"database_id": 1, "sql": "select 1", "label": "query"},
+ "description",
+ ),
+ (UpdateDashboardRequest, {"identifier": 1}, "description"),
+ ],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_unsanitized_sibling_names_remain_literal(
+ model: type[BaseModel], payload: dict[str, Any], field: str, value: str
+) -> None:
+ """Non-sanitizer paths retain their existing literal identifier/text contract."""
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "Users aged <30",
+ "Revenue <$1M",
+ "Love <3 charts",
+ "<<</b>x",
+ "&lt;</script>click= <b>📈",
+ ],
+)
+def test_sql_lab_title_remains_literal(value: str) -> None:
+ """SQL Lab tab titles trim whitespace without HTML sanitization."""
+ from superset.mcp_service.sql_lab.schemas import OpenSqlLabRequest
+
+ assert OpenSqlLabRequest(database_id=1, title=value).title == value
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("field", ["dashboard_title", "title", "name"])
+@pytest.mark.parametrize(
+ "rejected", ["<script>alert(1)</script>", "Weekly &am<b></b>p;lt;b&gt;KPIs"]
+)
+async def test_duplicate_dashboard_removed_or_unstable_title_wire_reason(
+ field: str, rejected: str
+) -> None:
+ """Removed or unstable markup is unsafe content, not an empty input."""
+ async with Client(make_title_server()) as client:
+ result = await client.call_tool_mcp(
+ "duplicate_dashboard", {"request": {"dashboard_id": 1, field: rejected}}
+ )
+ assert result.isError is True
+ assert result.content == [
+ TextContent(
+ type="text",
+ text="Error: Validation error in duplicate_dashboard: "
+ "request.dashboard_title: Contains disallowed content "
+ "(HTML, script or data: URL, event handler, or SQL keyword); "
+ "a 'data:' label must not be followed by a comma",
+ )
+ ]
+
+
+@pytest.mark.parametrize("model,payload,field", _TITLE_SANITIZATION_CASES)
+@pytest.mark.parametrize("character", [">", "\u00a0"])
+@pytest.mark.parametrize("at_limit", [True, False])
+def test_title_length_counts_plain_text(
+ model: type[BaseModel],
+ payload: dict[str, Any],
+ field: str,
+ character: str,
+ at_limit: bool,
+) -> None:
+ """Entity serialization must not inflate persisted titles or reject valid ones."""
+ limit = 250 if field == "chart_name" else 500
+ value = "x" * (limit - 2 + (not at_limit)) + character + "y"
+ if not at_limit:
+ with pytest.raises(ValidationError) as exc:
+ model.model_validate({**payload, field: value})
+ assert exc.value.errors()[0]["type"] == "string_too_long"
+ return
+ request = model.model_validate({**payload, field: value})
+ assert getattr(request, field) == value
+ assert len(getattr(request, field)) == limit
+ assert request.sanitization_warnings == []
+ assert getattr(model.model_validate(request.model_dump()), field) == value
+
+
+def test_builtin_name_validation_documented_for_administrators() -> None:
+ """Built-in validation guidance belongs with server administration."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ admin = (root / "docs/admin_docs/configuration/mcp-server.mdx").read_text()
+ extensions = (root / "docs/developer_docs/extensions/mcp.md").read_text()
+ for heading in ("Chart and dashboard titles", "Object-name validation"):
+ assert heading in admin
+ assert heading not in extensions
+ assert "Theme names retain their whitespace" in admin
+ assert "length validation applies after trimming" in admin
+
+
+def test_name_contract_changes_have_upgrade_guidance() -> None:
+ """Clients need migration guidance for blank renames and tighter name caps."""
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[3]
+ next_release = (
+ (root / "UPDATING.md").read_text().split("## Next", 1)[1].split("\n## ", 1)[0]
+ )
+ assert (
+ "`update_dashboard` rejects blank or whitespace-only `dashboard_title`"
+ in next_release
+ )
+ assert "chart names and theme names are capped at 250 characters" in next_release
+ assert "omit the field to keep the stored title" in next_release
+
+
Review Comment:
**🔴 High — `test_name_contract_changes_have_upgrade_guidance` will fail at the next release cut**
This test reads only the `## Next` section of UPDATING.md. At a release cut, a `## x.y.z` heading is inserted above the entries that ship; d76b896c9c did this for 6.1.0. Once this entry ships it is no longer under `## Next`, so the test fails in the release PR. No other unit test reads UPDATING.md, and the contract is already pinned by `test_update_dashboard_blank_title_wire_reason`, `test_chart_name_model_column_boundary` and `test_theme_name_model_column_boundary`. I suggest dropping it:
```suggestion
```
##########
superset/mcp_service/utils/sanitization.py:
##########
@@ -70,11 +70,36 @@ def _strip_html_tags(value: str) -> str:
# url_schemes=set() blocks all URL schemes in any remaining attributes
cleaned = nh3.clean(decoded, tags=set(), url_schemes=set())
- # Only restore & → & to preserve ampersands in display text (e.g. "A & B").
- # Do NOT use html.unescape() here: nh3 may pass through HTML entities from
- # the input (e.g. <script>), and a full unescape would re-introduce
- # raw angle brackets, creating an XSS vector.
- return cleaned.replace("&", "&")
+ # Restore brackets only before comparison punctuation, numbers or whitespace.
+ # Non-ASCII letters can case-fold into tag names in downstream renderers;
+ # leave those and reconstructed tag openers escaped.
+ # Normalize removable characters before deciding whether a bracket is safe;
+ # otherwise a later Unicode strip could turn <\u200bscript into markup.
+ cleaned = _remove_dangerous_unicode(cleaned)
+ # Greater-than signs and NBSP cannot open tags. Restore them so plain text
+ # neither changes on display nor outgrows the model-column length limits.
+ return (
+ re.sub(r"<(?=[\d\s$€£¥%+=.,:;)\]&-]|$)", "<", cleaned)
Review Comment:
**🔴 High — `<` before control whitespace now forms Slack control sequences**
The `\s` in the allowlist I suggested is too broad. It restores `<` before TAB/LF/CR, and `>` is now raw. Report titles go through `sanitize_title` (`superset/utils/file.py`), which strips control characters. So an MCP chart name `Q3 <\t!channel>` is stored as-is, and the Slack report message contains a live `<!channel>`. `<@U…>`, `<#C…|…>` and `<https://evil.example|Open dashboard>` behave the same way. At the previous head `>` stayed `>`, so none of these closed.
The fix keeps `<` escaped before control whitespace, unless only whitespace follows. Literal comparisons and the case-fold cases are unchanged, and the touched MCP tests pass with it:
```suggestion
re.sub(
# Control whitespace stays escaped: report titles strip it, which
# could join "<" to a Slack control sequence such as <!channel>.
r"<(?=[\d$€£¥%+=.,:;)\]&-]|[^\S\x00-\x1f\x7f-\x9f]|(?:\s| )*$)",
"<",
cleaned,
)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): report length and empty-title reasons for MCP title fields [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #45575:
URL: https://github.com/apache/superset/pull/45575#discussion_r4367130997
##########
superset-frontend/plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts:
##########
@@ -193,3 +196,27 @@ test('renders when __timestamp is serialized as a non-epoch string', () => {
expect(seriesNames).toEqual(['East', 'West']);
expect(series[0].data.map((d: any) => d.value)).toEqual([30, 10]);
});
+
+test.each([true, false])(
+ 'escapes literal series text in Rose tooltips (rich=%s)',
+ richTooltip => {
+ const name = 'Love <3 charts & <img src=x>';
+ const props = new ChartProps({
+ width: 800,
+ height: 600,
+ formData: { ...formData, richTooltip },
Review Comment:
Fixed in 214f0b4ce2781a32c33909c62154e017253e8670.
I set `dateTimeFormat` to `'<b>period</b>'` in the regression test 'escapes literal series text in Rose tooltips (rich=%s)' and assert the complete literal text with exactly one structural `<b>`. I reproduced the gap: with the original test, removing either period-label escape independently still passed. With the strengthened test, each removal fails its corresponding rich/plain case; restoring the escape passes.
The sibling sweep also supplies markup from registered number formatters and translated range text. All 18 individual escape-removal mutations fail DOM assertions, including the drilled Rose formatter in 'drilled Rose tooltips preserve literal series and period text'. Restored-source Jest: 3 suites, 32 tests passed (`CI=true npm run test -- --runInBand plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts plugins/plugin-chart-echarts/test/Rose/EchartsRose.test.tsx --coverage --coverageReporters=json`).
Siblings checked:
- superset-frontend/plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts:207 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/test/Rose/EchartsRose.test.tsx:190 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts:442 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:136 — not affected: series-name and formatted-value escapes are present; removing each separately fails the Rose tooltip regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:141 — not affected: rich period-label escape is present; removing it fails only the rich case.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:183 — not affected: plain period-label, series-name and formatted-value escapes are present; removing each separately fails the plain case.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/EchartsRose.tsx:81 — not affected: drilled period-label, series-name and formatted-value escapes are present; removing each separately fails the drilled regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:230 — not affected: grouped-category escape is present; removing it fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:234 — not affected: translated Range and containing-band escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:237 — not affected: metric-label and measure-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:266 — not affected: range-label and range-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:283 — not affected: marker-label and marker-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts:1046 — not affected: the shared encodeHTML wrapper is unchanged.
##########
superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts:
##########
@@ -424,3 +424,38 @@ test('keeps exact-case dimensions and uses per-index fallbacks for short labels'
.map(series => series.markLine?.data[0].label.formatter()),
).toEqual(['stretch', '260.0']);
});
+
+test('escapes literal comparison text in every Bullet tooltip', () => {
+ const label = 'Users <30 & <img src=x>';
+ const metric = 'Total <3';
Review Comment:
Fixed in 214f0b4ce2781a32c33909c62154e017253e8670.
I changed the metric to `'<b>Total <3</b>'` in the regression test 'escapes literal comparison text in every Bullet tooltip'. Its literal text must survive, and each tooltip must have exactly one structural `<b>`. I reproduced the gap: the original test passes without `escapeHtml(metricLabel)`; the strengthened test fails that same mutation and passes with the escape restored.
The sibling sweep also exercises markup in formatted numbers, translated range text and Rose period labels. All 18 individual escape-removal mutations fail DOM assertions. Restored-source Jest: 3 suites, 32 tests passed (`CI=true npm run test -- --runInBand plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts plugins/plugin-chart-echarts/test/Rose/EchartsRose.test.tsx --coverage --coverageReporters=json`).
Siblings checked:
- superset-frontend/plugins/plugin-chart-echarts/test/Rose/transformProps.test.ts:207 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/test/Rose/EchartsRose.test.tsx:190 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts:442 — fixed in 214f0b4ce2781a32c33909c62154e017253e8670
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:136 — not affected: series-name and formatted-value escapes are present; removing each separately fails the Rose tooltip regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:141 — not affected: rich period-label escape is present; removing it fails only the rich case.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/transformProps.ts:183 — not affected: plain period-label, series-name and formatted-value escapes are present; removing each separately fails the plain case.
- superset-frontend/plugins/plugin-chart-echarts/src/Rose/EchartsRose.tsx:81 — not affected: drilled period-label, series-name and formatted-value escapes are present; removing each separately fails the drilled regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:230 — not affected: grouped-category escape is present; removing it fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:234 — not affected: translated Range and containing-band escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:237 — not affected: metric-label and measure-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:266 — not affected: range-label and range-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts:283 — not affected: marker-label and marker-value escapes are present; removing each separately fails the Bullet regression.
- superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts:1046 — not affected: the shared encodeHTML wrapper is unchanged.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org