You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by en...@apache.org on 2026/06/04 20:44:23 UTC
(superset) 02/08: fix(extensions): validate settings payload and harden chatbot resolver
This is an automated email from the ASF dual-hosted git repository.
EnxDev pushed a commit to branch test/chatbot-local
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 579c8d83776f0cbcf2d335b120a8c4f909512cda
Author: Enzo Martellucci <en...@gmail.com>
AuthorDate: Thu Jun 4 09:01:26 2026 +0200
fix(extensions): validate settings payload and harden chatbot resolver
Addresses remaining PR review comments:
- Reject invalid active_chatbot_id types (e.g. ints) and oversized ids with
a 400 instead of silently coercing to null / failing at the DB layer.
- Reject oversized / non-string enabled-map keys with a 400 before the DB
enforces the column length.
- Share the id column length via EXTENSION_ID_MAX_LENGTH so validation and
the schema cannot drift.
- Chatbot resolver now falls through to the next candidate when a view id
fails to resolve, instead of returning undefined on the first miss.
Co-Authored-By: Claude Opus 4.8 (1M context) <no...@anthropic.com>
---
superset-frontend/src/core/chatbot/index.test.ts | 31 +++++++++
superset-frontend/src/core/chatbot/index.ts | 19 +++---
superset/extensions/api.py | 36 ++++++++++-
superset/extensions/models.py | 8 ++-
tests/unit_tests/extensions/test_settings.py | 80 ++++++++++++++++++++++++
5 files changed, 164 insertions(+), 10 deletions(-)
diff --git a/superset-frontend/src/core/chatbot/index.test.ts b/superset-frontend/src/core/chatbot/index.test.ts
index 80cd1d51e95..3dfaa70a134 100644
--- a/superset-frontend/src/core/chatbot/index.test.ts
+++ b/superset-frontend/src/core/chatbot/index.test.ts
@@ -17,6 +17,7 @@
* under the License.
*/
import React from 'react';
+import * as viewsModule from 'src/core/views';
import { views } from 'src/core/views';
import { CHATBOT_LOCATION } from 'src/views/contributions';
import { getActiveChatbot } from './index';
@@ -154,6 +155,36 @@ test('getActiveChatbot excludes disabled extensions before applying admin pin',
expect(active?.id).toBe('first.chatbot');
});
+test('getActiveChatbot falls through to the next candidate when one fails to resolve', () => {
+ const secondProvider = () => React.createElement('div', null, 'Second');
+ disposables.push(
+ views.registerView(
+ { id: 'first.chatbot', name: 'First Chatbot' },
+ CHATBOT_LOCATION,
+ () => React.createElement('div', null, 'First'),
+ ),
+ views.registerView(
+ { id: 'second.chatbot', name: 'Second Chatbot' },
+ CHATBOT_LOCATION,
+ secondProvider,
+ ),
+ );
+
+ // Simulate a stale registration: the id is still listed but its provider no
+ // longer resolves. Resolution must skip it instead of returning undefined.
+ jest
+ .spyOn(viewsModule, 'getViewProvider')
+ .mockImplementation((location, id) =>
+ id === 'first.chatbot' ? undefined : secondProvider,
+ );
+
+ const active = getActiveChatbot();
+ expect(active?.id).toBe('second.chatbot');
+ expect(active?.provider).toBe(secondProvider);
+
+ jest.restoreAllMocks();
+});
+
test('getActiveChatbot returns undefined when all candidates are disabled', () => {
disposables.push(
views.registerView(
diff --git a/superset-frontend/src/core/chatbot/index.ts b/superset-frontend/src/core/chatbot/index.ts
index 4cb92b4bc9a..5ed020063ae 100644
--- a/superset-frontend/src/core/chatbot/index.ts
+++ b/superset-frontend/src/core/chatbot/index.ts
@@ -73,15 +73,20 @@ export const getActiveChatbot = (
return undefined;
}
- const selectedId =
+ // Try the admin-pinned id first, then fall back through the remaining
+ // candidates in registration order. A candidate may fail to resolve if its
+ // registration became stale, so we keep looking instead of giving up.
+ const ordered =
adminSelectedId && candidates.includes(adminSelectedId)
- ? adminSelectedId
- : candidates[0];
+ ? [adminSelectedId, ...candidates.filter(id => id !== adminSelectedId)]
+ : candidates;
- const provider = getViewProvider(CHATBOT_LOCATION, selectedId);
- if (!provider) {
- return undefined;
+ for (const id of ordered) {
+ const provider = getViewProvider(CHATBOT_LOCATION, id);
+ if (provider) {
+ return { id, provider };
+ }
}
- return { id: selectedId, provider };
+ return undefined;
};
diff --git a/superset/extensions/api.py b/superset/extensions/api.py
index d7bc73cc02e..9f8965d964c 100644
--- a/superset/extensions/api.py
+++ b/superset/extensions/api.py
@@ -26,6 +26,7 @@ from flask.wrappers import Response
from flask_appbuilder.api import BaseApi, expose, protect, safe
from superset.extensions import security_manager
+from superset.extensions.models import EXTENSION_ID_MAX_LENGTH
from superset.extensions.settings import (
get_extension_settings,
update_extension_settings,
@@ -52,6 +53,23 @@ def _validate_segment(value: str) -> bool:
return bool(_SEGMENT_RE.match(value))
+def _is_valid_chatbot_id(value: Any) -> bool:
+ """active_chatbot_id must be null or a non-empty, length-bounded string."""
+ if value is None:
+ return True
+ return isinstance(value, str) and 0 < len(value) <= EXTENSION_ID_MAX_LENGTH
+
+
+def _are_valid_enabled_keys(enabled: Any) -> bool:
+ """The enabled map must be an object keyed by length-bounded extension ids."""
+ if not isinstance(enabled, dict):
+ return False
+ return all(
+ isinstance(key, str) and 0 < len(key) <= EXTENSION_ID_MAX_LENGTH
+ for key in enabled
+ )
+
+
class ExtensionsRestApi(BaseApi):
allow_browser_login = True
resource_name = "extensions"
@@ -449,7 +467,23 @@ class ExtensionsRestApi(BaseApi):
"""
if not security_manager.is_admin():
return self.response(403, message="Admin access required.")
- body = request.get_json(silent=True) or {}
+ body = request.get_json(silent=True)
+ if not isinstance(body, dict):
+ return self.response(400, message="Request body must be a JSON object.")
+ if "active_chatbot_id" in body and not _is_valid_chatbot_id(
+ body["active_chatbot_id"]
+ ):
+ return self.response(
+ 400,
+ message="active_chatbot_id must be null or a non-empty string "
+ f"of at most {EXTENSION_ID_MAX_LENGTH} characters.",
+ )
+ if "enabled" in body and not _are_valid_enabled_keys(body["enabled"]):
+ return self.response(
+ 400,
+ message="enabled keys must be non-empty strings of at most "
+ f"{EXTENSION_ID_MAX_LENGTH} characters.",
+ )
result = update_extension_settings(body)
return self.response(200, result=result)
diff --git a/superset/extensions/models.py b/superset/extensions/models.py
index 623b839134a..caf2479d5a3 100644
--- a/superset/extensions/models.py
+++ b/superset/extensions/models.py
@@ -20,18 +20,22 @@
from flask_appbuilder import Model
from sqlalchemy import Boolean, Column, Integer, String
+# Shared column length for extension/chatbot identifiers; reused by request
+# validation so oversized keys are rejected with a 400 before hitting the DB.
+EXTENSION_ID_MAX_LENGTH = 250
+
class ExtensionSettings(Model): # pylint: disable=too-few-public-methods
"""Global admin settings for extensions (singleton row, id=1)."""
__tablename__ = "extension_settings"
id = Column(Integer, primary_key=True)
- active_chatbot_id = Column(String(250), nullable=True)
+ active_chatbot_id = Column(String(EXTENSION_ID_MAX_LENGTH), nullable=True)
class ExtensionEnabled(Model): # pylint: disable=too-few-public-methods
"""Per-extension enable/disable flag."""
__tablename__ = "extension_enabled"
- extension_id = Column(String(250), primary_key=True)
+ extension_id = Column(String(EXTENSION_ID_MAX_LENGTH), primary_key=True)
enabled = Column(Boolean, nullable=False, default=True)
diff --git a/tests/unit_tests/extensions/test_settings.py b/tests/unit_tests/extensions/test_settings.py
index 22466ab072e..efe96de1d6e 100644
--- a/tests/unit_tests/extensions/test_settings.py
+++ b/tests/unit_tests/extensions/test_settings.py
@@ -205,3 +205,83 @@ class TestPutSettingsEndpoint:
)
resp = client.put("/api/v1/extensions/settings", json={})
assert resp.status_code == 200
+
+ def test_non_object_body_rejected(
+ self, client: Any, full_api_access: None, mocker: Any
+ ) -> None:
+ mocker.patch(
+ "superset.extensions.api.security_manager.is_admin", return_value=True
+ )
+ update = mocker.patch(
+ "superset.extensions.api.update_extension_settings",
+ )
+ resp = client.put("/api/v1/extensions/settings", json=["not", "an", "object"])
+ assert resp.status_code == 400
+ update.assert_not_called()
+
+ def test_non_string_active_chatbot_id_rejected(
+ self, client: Any, full_api_access: None, mocker: Any
+ ) -> None:
+ mocker.patch(
+ "superset.extensions.api.security_manager.is_admin", return_value=True
+ )
+ update = mocker.patch(
+ "superset.extensions.api.update_extension_settings",
+ )
+ # An int must be rejected with a 400, not silently coerced to null.
+ resp = client.put(
+ "/api/v1/extensions/settings", json={"active_chatbot_id": 123}
+ )
+ assert resp.status_code == 400
+ update.assert_not_called()
+
+ def test_null_active_chatbot_id_is_accepted(
+ self, client: Any, full_api_access: None, mocker: Any
+ ) -> None:
+ mocker.patch(
+ "superset.extensions.api.security_manager.is_admin", return_value=True
+ )
+ mocker.patch(
+ "superset.extensions.api.update_extension_settings",
+ return_value={"active_chatbot_id": None, "enabled": {}},
+ )
+ resp = client.put(
+ "/api/v1/extensions/settings", json={"active_chatbot_id": None}
+ )
+ assert resp.status_code == 200
+
+ def test_oversized_active_chatbot_id_rejected(
+ self, client: Any, full_api_access: None, mocker: Any
+ ) -> None:
+ from superset.extensions.models import EXTENSION_ID_MAX_LENGTH
+
+ mocker.patch(
+ "superset.extensions.api.security_manager.is_admin", return_value=True
+ )
+ update = mocker.patch(
+ "superset.extensions.api.update_extension_settings",
+ )
+ resp = client.put(
+ "/api/v1/extensions/settings",
+ json={"active_chatbot_id": "x" * (EXTENSION_ID_MAX_LENGTH + 1)},
+ )
+ assert resp.status_code == 400
+ update.assert_not_called()
+
+ def test_oversized_enabled_key_rejected(
+ self, client: Any, full_api_access: None, mocker: Any
+ ) -> None:
+ from superset.extensions.models import EXTENSION_ID_MAX_LENGTH
+
+ mocker.patch(
+ "superset.extensions.api.security_manager.is_admin", return_value=True
+ )
+ update = mocker.patch(
+ "superset.extensions.api.update_extension_settings",
+ )
+ resp = client.put(
+ "/api/v1/extensions/settings",
+ json={"enabled": {"x" * (EXTENSION_ID_MAX_LENGTH + 1): True}},
+ )
+ assert resp.status_code == 400
+ update.assert_not_called()