Skip to content

Commit efc57b6

Browse files
eschuthoclaude
andauthored
fix(api): return 400 instead of 500 for wrong-shape query_context in legacy /api/v1/query/ (#45927)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent dd362af commit efc57b6

4 files changed

Lines changed: 136 additions & 7 deletions

File tree

‎superset/translations/messages.pot‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19316,6 +19316,10 @@ msgstr ""
1931619316
msgid "query"
1931719317
msgstr ""
1931819318

19319+
#, python-format
19320+
msgid "query_context is invalid: %(details)s"
19321+
msgstr ""
19322+
1931919323
msgid "query_context must be a JSON object"
1932019324
msgstr ""
1932119325

‎superset/views/api.py‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
# under the License.
1717
from __future__ import annotations
1818

19+
import inspect
1920
from typing import Any, TYPE_CHECKING
2021

2122
from flask import request
@@ -31,6 +32,7 @@
3132
TimeRangeParseFailError,
3233
)
3334
from superset.daos.chart import ChartDAO
35+
from superset.daos.datasource import DatasourceDAO
3436
from superset.exceptions import QueryObjectValidationError
3537
from superset.legacy import update_time_range
3638
from superset.superset_typing import FlaskResponse
@@ -78,7 +80,9 @@ def query(self) -> FlaskResponse:
7880
) from ex
7981
if not isinstance(query_context_params, dict):
8082
raise QueryObjectValidationError(_("query_context must be a JSON object"))
81-
query_context = self.get_query_context_factory().create(**query_context_params)
83+
factory = self.get_query_context_factory()
84+
self._validate_query_context_shape(factory, query_context_params)
85+
query_context = factory.create(**query_context_params)
8286
query_context.raise_for_access()
8387
result = query_context.get_payload()
8488
payload_json = result["queries"]
@@ -145,6 +149,68 @@ def time_range(self, **kwargs: Any) -> FlaskResponse:
145149
error_msg = {"message": _("Unexpected time range: %(error)s", error=error)}
146150
return self.json_response(error_msg, 400)
147151

152+
@staticmethod
153+
def _validate_query_context_shape(
154+
factory: QueryContextFactory, params: dict[str, Any]
155+
) -> None:
156+
"""
157+
Reject a ``query_context`` that cannot be passed to ``factory.create``.
158+
159+
Binding the keys against the factory signature and checking the types of
160+
the required members turns user-fixable input errors into a 400 without
161+
guarding the ``create`` call itself, so internal errors still surface.
162+
"""
163+
signature = inspect.signature(factory.create)
164+
try:
165+
signature.bind(**params)
166+
except TypeError as ex:
167+
unexpected = sorted(set(params) - set(signature.parameters))
168+
missing = sorted(
169+
name
170+
for name, parameter in signature.parameters.items()
171+
if parameter.default is inspect.Parameter.empty and name not in params
172+
)
173+
details = []
174+
if unexpected:
175+
details.append(f"unexpected keys: {', '.join(unexpected)}")
176+
if missing:
177+
details.append(f"missing keys: {', '.join(missing)}")
178+
raise QueryObjectValidationError(
179+
_("query_context is invalid: %(details)s", details="; ".join(details))
180+
) from ex
181+
182+
datasource = params["datasource"]
183+
if (
184+
not isinstance(datasource, dict)
185+
or "id" not in datasource
186+
or not isinstance(datasource.get("type"), str)
187+
or datasource["type"] not in DatasourceDAO.sources
188+
):
189+
raise QueryObjectValidationError(
190+
_(
191+
"query_context is invalid: %(details)s",
192+
details="datasource must be an object with an id and a valid type",
193+
)
194+
)
195+
form_data = params.get("form_data")
196+
if form_data is not None and not isinstance(form_data, dict):
197+
raise QueryObjectValidationError(
198+
_(
199+
"query_context is invalid: %(details)s",
200+
details="form_data must be an object",
201+
)
202+
)
203+
queries = params["queries"]
204+
if not isinstance(queries, list) or not all(
205+
isinstance(query, dict) for query in queries
206+
):
207+
raise QueryObjectValidationError(
208+
_(
209+
"query_context is invalid: %(details)s",
210+
details="queries must be a list of objects",
211+
)
212+
)
213+
148214
def get_query_context_factory(self) -> QueryContextFactory:
149215
if self.query_context_factory is None:
150216
# pylint: disable=import-outside-toplevel

‎tests/unit_tests/views/test_api_query.py‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@
2727
import pytest
2828
from pytest_mock import MockerFixture
2929

30+
from superset.utils import json
31+
3032
QUERY_URL = "/api/v1/query/"
33+
VALID_DATASOURCE = {"id": 1, "type": "table"}
3134

3235

3336
@pytest.mark.parametrize(
@@ -69,9 +72,64 @@ def test_query_valid_query_context_reaches_factory(
6972
)
7073

7174
response = client.post(
72-
QUERY_URL, data={"query_context": '{"datasource": {"id": 1}, "queries": []}'}
75+
QUERY_URL,
76+
data={
77+
"query_context": json.dumps({"datasource": VALID_DATASOURCE, "queries": []})
78+
},
7379
)
7480

7581
assert response.status_code == 200
76-
create.assert_called_once_with(datasource={"id": 1}, queries=[])
82+
create.assert_called_once_with(datasource=VALID_DATASOURCE, queries=[])
7783
query_context.raise_for_access.assert_called_once()
84+
85+
86+
@pytest.mark.parametrize(
87+
"query_context",
88+
[
89+
{},
90+
{"datasource": {"id": 1, "type": "table"}},
91+
{"queries": []},
92+
{"datasource": {"id": 1, "type": "table"}, "queries": [], "bogus": 1},
93+
{"datasource": "not-an-object", "queries": []},
94+
{"datasource": [1], "queries": []},
95+
{"datasource": {}, "queries": []},
96+
{"datasource": {"id": 1}, "queries": []},
97+
{"datasource": {"type": "table"}, "queries": []},
98+
{"datasource": {"id": 1, "type": "bogus"}, "queries": []},
99+
{"datasource": {"id": 1, "type": None}, "queries": []},
100+
{"datasource": {"id": 1, "type": "view"}, "queries": []},
101+
{"datasource": {"id": 1, "type": "table"}, "queries": [], "form_data": "x"},
102+
{"datasource": {"id": 1, "type": "table"}, "queries": {"a": 1}},
103+
{"datasource": {"id": 1, "type": "table"}, "queries": ["not-an-object"]},
104+
],
105+
ids=[
106+
"empty_object",
107+
"missing_queries",
108+
"missing_datasource",
109+
"unknown_key",
110+
"datasource_string",
111+
"datasource_list",
112+
"datasource_empty",
113+
"datasource_missing_type",
114+
"datasource_missing_id",
115+
"datasource_invalid_type",
116+
"datasource_null_type",
117+
"datasource_unsupported_type",
118+
"form_data_string",
119+
"queries_object",
120+
"queries_non_object_item",
121+
],
122+
)
123+
def test_query_returns_400_for_malformed_query_context_shape(
124+
client: Any,
125+
full_api_access: None,
126+
query_context: dict[str, Any],
127+
) -> None:
128+
"""A JSON object that does not match the factory's signature, or whose
129+
``datasource``/``queries`` have the wrong type, is a user-fixable input error
130+
and yields a 400 rather than a raw ``TypeError`` surfacing as a 500.
131+
"""
132+
response = client.post(QUERY_URL, data={"query_context": json.dumps(query_context)})
133+
134+
assert response.status_code == 400, response.get_data(as_text=True)
135+
assert "query_context is invalid" in response.get_data(as_text=True)

‎tests/unit_tests/views/test_base.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,9 @@ def test_locale_language_extraction_preserves_region_when_configured(
268268
assert _extract_language(locale_str, languages) == expected_language
269269

270270

271+
_VALID_QUERY_CONTEXT = '{"datasource": {"id": 1, "type": "table"}, "queries": []}'
272+
273+
271274
def test_api_query_returns_json_content_type() -> None:
272275
"""``Api.query`` returns a response with a JSON content type.
273276
@@ -294,7 +297,7 @@ def test_api_query_returns_json_content_type() -> None:
294297

295298
with patch.object(api_view, "get_query_context_factory", return_value=factory):
296299
with current_app.test_request_context(
297-
data={"query_context": '{"datasource": {"id": 1}}'}
300+
data={"query_context": _VALID_QUERY_CONTEXT}
298301
):
299302
response = handler(api_view)
300303

@@ -341,9 +344,7 @@ def _run_api_query(*, is_guest: bool) -> list[dict[str, Any]]:
341344
"superset.security.SupersetSecurityManager.can_access",
342345
return_value=False,
343346
),
344-
current_app.test_request_context(
345-
data={"query_context": '{"datasource": {"id": 1}}'}
346-
),
347+
current_app.test_request_context(data={"query_context": _VALID_QUERY_CONTEXT}),
347348
):
348349
response = handler(api_view)
349350

0 commit comments

Comments
 (0)