codeant-ai-for-open-source[bot] commented on code in PR #41497: URL: https://github.com/apache/superset/pull/41497#discussion_r3545827258
########## superset/mcp_service/theme/schemas.py: ########## @@ -0,0 +1,301 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Pydantic schemas for theme-related responses +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any, Dict, List, Literal + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_serializer, + model_validator, + PositiveInt, +) + +from superset.daos.base import ColumnOperator, ColumnOperatorEnum +from superset.mcp_service.constants import DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE +from superset.mcp_service.system.schemas import PaginationInfo +from superset.mcp_service.utils.response_utils import humanize_timestamp +from superset.mcp_service.utils.sanitization import sanitize_for_llm_context +from superset.mcp_service.utils.schema_utils import ( + parse_json_or_list, + parse_json_or_model_list, +) + + +class ThemeFilter(ColumnOperator): + """ + Filter object for theme listing. + col: The column to filter on. Must be one of the allowed filter fields. + opr: The operator to use. Must be one of the supported operators. + value: The value to filter by (type depends on col and opr). + """ + + col: Literal["theme_name"] = Field( + ..., + description="Column to filter on. Supported: 'theme_name' (string match).", + ) + opr: ColumnOperatorEnum = Field( + ..., + description="Operator to use. Common operators: 'eq' (equals), " + "'ct' (contains), 'sw' (starts with), 'ew' (ends with).", + ) + value: str | int | float | bool | List[str | int | float | bool] = Field( + ..., description="Value to filter by (type depends on col and opr)" + ) + + +class ThemeInfo(BaseModel): + """Theme metadata returned by MCP list/get tools.""" + + id: int | None = None + theme_name: str | None = None + json_data: str | None = Field( + None, description="Raw antd design-token JSON configuration as a string" + ) + uuid: str | None = None + is_system: bool | None = None + is_system_default: bool | None = None + is_system_dark: bool | None = None + changed_on: str | datetime | None = Field( + None, description="Last modification timestamp" + ) + changed_on_humanized: str | None = Field( + None, description="Humanized modification time" + ) + created_on: str | datetime | None = Field(None, description="Creation timestamp") + created_on_humanized: str | None = Field( + None, description="Humanized creation time" + ) + model_config = ConfigDict( + from_attributes=True, + ser_json_timedelta="iso8601", + populate_by_name=True, + ) + + @model_serializer(mode="wrap") + def _filter_fields_by_context(self, serializer: Any, info: Any) -> Dict[str, Any]: + """Filter serialized fields to those requested via select_columns context.""" + data: Dict[str, Any] = serializer(self) + if info.context and isinstance(info.context, dict): + select_columns = info.context.get("select_columns") + if select_columns: + requested_fields = set(select_columns) + return {k: v for k, v in data.items() if k in requested_fields} + return data + + +class ThemeList(BaseModel): + themes: List[ThemeInfo] + count: int + total_count: int + page: int + page_size: int + total_pages: int + has_previous: bool + has_next: bool + columns_requested: List[str] = Field(default_factory=list) + columns_loaded: List[str] = Field(default_factory=list) + columns_available: List[str] = Field(default_factory=list) + sortable_columns: List[str] = Field(default_factory=list) + filters_applied: List[ThemeFilter] = Field(default_factory=list) + pagination: PaginationInfo | None = None + timestamp: datetime | None = None + model_config = ConfigDict(ser_json_timedelta="iso8601") + + +class ListThemesRequest(BaseModel): + """Request schema for list_themes.""" + + filters: Annotated[ + List[ThemeFilter], + Field( + default_factory=list, + description="List of filter objects (column, operator, value). Each " + "filter has 'col', 'opr', and 'value' properties. Cannot be used " + "together with 'search'.", + ), + ] + select_columns: Annotated[ + List[str], + Field( + default_factory=list, + description="List of columns to select. Defaults to common columns if not " + "specified.", + ), + ] + search: Annotated[ + str | None, + Field( + default=None, + description="Text search string to match against theme name. Cannot be " + "used together with 'filters'.", + ), + ] + order_column: Annotated[ + str | None, Field(default=None, description="Column to order results by") + ] + order_direction: Annotated[ + Literal["asc", "desc"], + Field( + default="desc", + description="Direction to order results ('asc' or 'desc')", + ), + ] + page: Annotated[ + PositiveInt, + Field(default=1, description="Page number for pagination (1-based)"), + ] + page_size: Annotated[ + int, + Field( + default=DEFAULT_PAGE_SIZE, + gt=0, + le=MAX_PAGE_SIZE, + description=f"Number of items per page (max {MAX_PAGE_SIZE})", + ), + ] + + @field_validator("filters", mode="before") + @classmethod + def parse_filters(cls, v: Any) -> List[ThemeFilter]: + return parse_json_or_model_list(v, ThemeFilter, "filters") + + @field_validator("select_columns", mode="before") + @classmethod + def parse_columns(cls, v: Any) -> List[str]: + return parse_json_or_list(v, "select_columns") + + @model_validator(mode="after") + def validate_search_and_filters(self) -> "ListThemesRequest": + if self.search and self.filters: + raise ValueError( + "Cannot use both 'search' and 'filters' parameters simultaneously. " + "Use either 'search' for text-based searching or 'filters' for " + "precise column-based filtering, but not both." + ) + return self + + +class ThemeError(BaseModel): + error: str = Field(..., description="Error message") + error_type: str = Field(..., description="Type of error") + timestamp: str | datetime | None = Field(None, description="Error timestamp") + model_config = ConfigDict(ser_json_timedelta="iso8601") Review Comment: **Suggestion:** `ThemeError.error` is returned to the LLM context without sanitization, but `get_theme_info` can include user-controlled `identifier` content in not-found errors; that allows prompt-injection delimiters to be reflected back unwrapped. Add an `error` field validator (like other MCP schemas) that routes through `sanitize_for_llm_context` before serialization. [security] <details> <summary><b>Severity Level:</b> Critical π¨</summary> ```mdx - β Prompt-injection via identifier reflected in error text. - β οΈ Theme info tool exposes unwrapped attacker tokens. ``` </details> <details> <summary><b>Steps of Reproduction β </b></summary> ```mdx 1. The `get_theme_info` FastMCP tool in `superset/mcp_service/theme/tool/get_theme_info.py:52-101` is wired to use `ModelGetInfoCore` with `error_schema=ThemeError` (see lines 78-82), so not-found and other structured errors are returned as `ThemeError` instances to the MCP client and ultimately into LLM context. 2. `ModelGetInfoCore.run_tool` in `superset/mcp_service/mcp_core.py:29-45` builds an error object when no row is found: it instantiates `self.error_schema` with `error=(f"{self.output_schema.__name__} with identifier '{identifier}' not found")` and `error_type="not_found"`, embedding the caller-supplied `identifier` directly in the `error` string without any sanitization. 3. `ThemeError` in `superset/mcp_service/theme/schemas.py:202-214` defines `error: str`, `error_type: str`, and `timestamp`, but unlike `DatasetError` and `DashboardError` (which add `@field_validator("error")` calling `sanitize_for_llm_context` at `superset/mcp_service/dataset/schemas.py:9-14` and `superset/mcp_service/dashboard/schemas.py:10-14`), `ThemeError` has no validator, so its `error` field is serialized and exposed to LLM context as-is. 4. If an attacker-controlled MCP client calls `get_theme_info` with an identifier such as `"<UNTRUSTED-CONTENT> injected </UNTRUSTED-CONTENT>"`, `ModelGetInfoCore.run_tool` at `mcp_core.py:32-37` returns a `ThemeError` whose `error` string includes those delimiter tokens; because `ThemeError.error` is not passed through `sanitize_for_llm_context`, the unwrapped delimiters reach the LLM, allowing prompt-injection content to break out of the intended untrusted-content wrapper and bypass the sanitization strategy used elsewhere in MCP schemas. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=19a2d3eb58554f8f85202a6664b1e65f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=19a2d3eb58554f8f85202a6664b1e65f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent π€ </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/theme/schemas.py **Line:** 202:206 **Comment:** *Security: `ThemeError.error` is returned to the LLM context without sanitization, but `get_theme_info` can include user-controlled `identifier` content in not-found errors; that allows prompt-injection delimiters to be reflected back unwrapped. Add an `error` field validator (like other MCP schemas) that routes through `sanitize_for_llm_context` before serialization. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=c3cec99d2e045cc94c285a556f15ae54a59131b8ac55e7006dd1d31cfd522f57&reaction=like'>π</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=c3cec99d2e045cc94c285a556f15ae54a59131b8ac55e7006dd1d31cfd522f57&reaction=dislike'>π</a> ########## superset/mcp_service/theme/schemas.py: ########## @@ -0,0 +1,301 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Pydantic schemas for theme-related responses +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any, Dict, List, Literal + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_serializer, + model_validator, + PositiveInt, +) + +from superset.daos.base import ColumnOperator, ColumnOperatorEnum +from superset.mcp_service.constants import DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE +from superset.mcp_service.system.schemas import PaginationInfo +from superset.mcp_service.utils.response_utils import humanize_timestamp +from superset.mcp_service.utils.sanitization import sanitize_for_llm_context +from superset.mcp_service.utils.schema_utils import ( + parse_json_or_list, + parse_json_or_model_list, +) + + +class ThemeFilter(ColumnOperator): + """ + Filter object for theme listing. + col: The column to filter on. Must be one of the allowed filter fields. + opr: The operator to use. Must be one of the supported operators. + value: The value to filter by (type depends on col and opr). + """ + + col: Literal["theme_name"] = Field( + ..., + description="Column to filter on. Supported: 'theme_name' (string match).", + ) + opr: ColumnOperatorEnum = Field( + ..., + description="Operator to use. Common operators: 'eq' (equals), " + "'ct' (contains), 'sw' (starts with), 'ew' (ends with).", + ) + value: str | int | float | bool | List[str | int | float | bool] = Field( + ..., description="Value to filter by (type depends on col and opr)" + ) + + +class ThemeInfo(BaseModel): + """Theme metadata returned by MCP list/get tools.""" + + id: int | None = None + theme_name: str | None = None + json_data: str | None = Field( + None, description="Raw antd design-token JSON configuration as a string" + ) + uuid: str | None = None + is_system: bool | None = None + is_system_default: bool | None = None + is_system_dark: bool | None = None + changed_on: str | datetime | None = Field( + None, description="Last modification timestamp" + ) + changed_on_humanized: str | None = Field( + None, description="Humanized modification time" + ) + created_on: str | datetime | None = Field(None, description="Creation timestamp") + created_on_humanized: str | None = Field( + None, description="Humanized creation time" + ) + model_config = ConfigDict( + from_attributes=True, + ser_json_timedelta="iso8601", + populate_by_name=True, + ) + + @model_serializer(mode="wrap") + def _filter_fields_by_context(self, serializer: Any, info: Any) -> Dict[str, Any]: + """Filter serialized fields to those requested via select_columns context.""" + data: Dict[str, Any] = serializer(self) + if info.context and isinstance(info.context, dict): + select_columns = info.context.get("select_columns") + if select_columns: + requested_fields = set(select_columns) + return {k: v for k, v in data.items() if k in requested_fields} + return data + + +class ThemeList(BaseModel): + themes: List[ThemeInfo] + count: int + total_count: int + page: int + page_size: int + total_pages: int + has_previous: bool + has_next: bool + columns_requested: List[str] = Field(default_factory=list) + columns_loaded: List[str] = Field(default_factory=list) + columns_available: List[str] = Field(default_factory=list) + sortable_columns: List[str] = Field(default_factory=list) + filters_applied: List[ThemeFilter] = Field(default_factory=list) + pagination: PaginationInfo | None = None + timestamp: datetime | None = None + model_config = ConfigDict(ser_json_timedelta="iso8601") + + +class ListThemesRequest(BaseModel): + """Request schema for list_themes.""" + + filters: Annotated[ + List[ThemeFilter], + Field( + default_factory=list, + description="List of filter objects (column, operator, value). Each " + "filter has 'col', 'opr', and 'value' properties. Cannot be used " + "together with 'search'.", + ), + ] + select_columns: Annotated[ + List[str], + Field( + default_factory=list, + description="List of columns to select. Defaults to common columns if not " + "specified.", + ), + ] + search: Annotated[ + str | None, + Field( + default=None, + description="Text search string to match against theme name. Cannot be " + "used together with 'filters'.", + ), + ] + order_column: Annotated[ + str | None, Field(default=None, description="Column to order results by") + ] + order_direction: Annotated[ + Literal["asc", "desc"], + Field( + default="desc", + description="Direction to order results ('asc' or 'desc')", + ), + ] + page: Annotated[ + PositiveInt, + Field(default=1, description="Page number for pagination (1-based)"), + ] + page_size: Annotated[ + int, + Field( + default=DEFAULT_PAGE_SIZE, + gt=0, + le=MAX_PAGE_SIZE, + description=f"Number of items per page (max {MAX_PAGE_SIZE})", + ), + ] + + @field_validator("filters", mode="before") + @classmethod + def parse_filters(cls, v: Any) -> List[ThemeFilter]: + return parse_json_or_model_list(v, ThemeFilter, "filters") + + @field_validator("select_columns", mode="before") + @classmethod + def parse_columns(cls, v: Any) -> List[str]: + return parse_json_or_list(v, "select_columns") + + @model_validator(mode="after") + def validate_search_and_filters(self) -> "ListThemesRequest": + if self.search and self.filters: + raise ValueError( + "Cannot use both 'search' and 'filters' parameters simultaneously. " + "Use either 'search' for text-based searching or 'filters' for " + "precise column-based filtering, but not both." + ) + return self + + +class ThemeError(BaseModel): + error: str = Field(..., description="Error message") + error_type: str = Field(..., description="Type of error") + timestamp: str | datetime | None = Field(None, description="Error timestamp") + model_config = ConfigDict(ser_json_timedelta="iso8601") + + @classmethod + def create(cls, error: str, error_type: str) -> "ThemeError": + from datetime import timezone + + return cls( + error=error, error_type=error_type, timestamp=datetime.now(timezone.utc) + ) + + +class GetThemeInfoRequest(BaseModel): + """Request schema for get_theme_info with numeric ID or UUID string.""" + + identifier: Annotated[ + int | str, + Field(description="Theme identifier β numeric ID or UUID string"), + ] + + +class CreateThemeRequest(BaseModel): + """Request schema for create_theme.""" + + theme_name: Annotated[ + str, + Field(description="Human-readable name for the theme"), + ] + json_data: Annotated[ + dict[str, Any] | str, + Field( + description="The antd design-token configuration. Accepts either a JSON " + "object (dict) or a JSON string." + ), + ] + + @field_validator("theme_name") + @classmethod + def reject_blank_theme_name(cls, value: str) -> str: + """Mirror the REST ThemePostSchema check: no empty/whitespace names.""" + if not value or not value.strip(): + raise ValueError("Theme name cannot be empty.") + return value + + +class CreateThemeResponse(BaseModel): + success: bool = Field(..., description="Whether the theme was created") + id: int | None = Field(None, description="ID of the created theme") + uuid: str | None = Field(None, description="UUID of the created theme") + theme_name: str | None = Field(None, description="Name of the created theme") + message: str | None = Field(None, description="Human-readable success message") + error: str | None = Field(None, description="Error message if creation failed") + error_type: str | None = Field(None, description="Type of error if creation failed") + + +def _sanitize_theme_info_for_llm_context(theme_info: ThemeInfo) -> ThemeInfo: + """Wrap user-controlled theme fields before LLM exposure. + + ``theme_name`` is user-supplied free text. ``json_data`` is structured + configuration, but its token values (font families, URLs, arbitrary antd + tokens) are equally user-controlled and pass ``is_valid_theme`` / + ``sanitize_theme_tokens`` untouched, so the whole JSON string is wrapped + as one untrusted block β the JSON stays parseable inside the delimiters, + and embedded delimiter tokens are escaped so a hostile value cannot close + the wrapper early. + """ + payload = theme_info.model_dump(mode="python") + payload["theme_name"] = sanitize_for_llm_context( + payload.get("theme_name"), + field_path=("theme_name",), + ) + payload["json_data"] = sanitize_for_llm_context( + payload.get("json_data"), + field_path=("json_data",), + ) Review Comment: **Suggestion:** `json_data` is being wrapped with LLM untrusted-content delimiters, which turns a valid JSON string into a non-JSON payload. That breaks interoperability with `create_theme`, which expects `json_data` to be parseable JSON when passed as a string, so a get/list β create round-trip will fail with JSON decode errors. Keep delimiter-escaping for safety, but do not wrapper-prefix/suffix this field if you need it to remain machine-parseable. [api mismatch] <details> <summary><b>Severity Level:</b> Major β οΈ</summary> ```mdx - β Theme JSON round-trip via MCP tools fails. - β οΈ Agents cannot clone existing themes via JSON string. ``` </details> <details> <summary><b>Steps of Reproduction β </b></summary> ```mdx 1. In `superset/mcp_service/theme/tool/create_theme.py:53-102`, the `create_theme` FastMCP tool parses `CreateThemeRequest.json_data` when it is a string using `json.loads(request.json_data)`, expecting a valid JSON string and returning a `CreateThemeResponse` error if decoding fails. 2. In `superset/mcp_service/theme/tool/get_theme_info.py:52-88`, the `get_theme_info` tool uses `ModelGetInfoCore` with `serializer=serialize_theme_object` from `superset/mcp_service/theme/schemas.py:283-301` to build a `ThemeInfo` response, including the stored `theme.json_data` string. 3. `serialize_theme_object` constructs a `ThemeInfo` and then passes it through `_sanitize_theme_info_for_llm_context` at `superset/mcp_service/theme/schemas.py:260-280`, where `payload["json_data"]` is transformed by `sanitize_for_llm_context` with `field_path=("json_data",)`; `sanitize_for_llm_context` in `superset/mcp_service/utils/sanitization.py:98-113,155-181` wraps string values with `<UNTRUSTED-CONTENT>` delimiters, turning a pure JSON string (e.g. `{"token":{"colorPrimary":"#1d4ed8"}}`) into a non-JSON payload like `<UNTRUSTED-CONTENT>\n{"token":{"colorPrimary":"#1d4ed8"}}\n</UNTRUSTED-CONTENT>`. 4. A realistic MCP agent workflow is to call `get_theme_info` (or `list_themes` at `superset/mcp_service/theme/tool/list_themes.py:76-154`, which also uses `serialize_theme_object`) to discover an existing themeβs `json_data`, then pass that string directly as `CreateThemeRequest.json_data` into `create_theme`; when `create_theme` executes `json.loads(request.json_data)` on the wrapped string at `create_theme.py:82-86`, it raises `json.JSONDecodeError`, producing a `CreateThemeResponse` with `success=False` and a `ValidationError` message instead of cloning the theme, so the intended get/list β create round-trip fails. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=851150a429094fc38ebfd653ea33710b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=851150a429094fc38ebfd653ea33710b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent π€ </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/theme/schemas.py **Line:** 276:279 **Comment:** *Api Mismatch: `json_data` is being wrapped with LLM untrusted-content delimiters, which turns a valid JSON string into a non-JSON payload. That breaks interoperability with `create_theme`, which expects `json_data` to be parseable JSON when passed as a string, so a get/list β create round-trip will fail with JSON decode errors. Keep delimiter-escaping for safety, but do not wrapper-prefix/suffix this field if you need it to remain machine-parseable. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=b00816832f98498cbf77047ecac9801948e4dd1ae8ba3d6a0555ce8f057a6d75&reaction=like'>π</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=b00816832f98498cbf77047ecac9801948e4dd1ae8ba3d6a0555ce8f057a6d75&reaction=dislike'>π</a> -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
