From 8c9ffdb2dab555d21f16dfd753d8527c7c76aadf Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Mon, 9 Nov 2026 15:04:59 +0800 Subject: [PATCH 01/12] refactor(api): release moderation lookup sessions before external calls --- api/core/moderation/api/api.py | 55 +-- .../core/moderation/api/test_api.py | 367 +++++++++++------- 2 files changed, 252 insertions(+), 170 deletions(-) diff --git a/api/core/moderation/api/api.py b/api/core/moderation/api/api.py index 361edf5c574314..b199baa76c8027 100644 --- a/api/core/moderation/api/api.py +++ b/api/core/moderation/api/api.py @@ -2,12 +2,11 @@ from pydantic import BaseModel, Field from sqlalchemy import select -from sqlalchemy.orm import scoped_session +from core.db.session_factory import session_factory from core.extension.api_based_extension_requestor import APIBasedExtensionPoint, APIBasedExtensionRequestor from core.helper.encrypter import decrypt_token from core.moderation.base import Moderation, ModerationAction, ModerationInputsResult, ModerationOutputsResult -from extensions.ext_database import db from models.api_based_extension import APIBasedExtension @@ -27,13 +26,11 @@ class ApiModeration(Moderation): @classmethod @override - def validate_config(cls, tenant_id: str, config: dict[str, Any]): - """ - Validate the incoming form config data. + def validate_config(cls, tenant_id: str, config: dict[str, Any]) -> None: + """Validate form settings and require an extension owned by the workspace. - :param tenant_id: the id of workspace - :param config: the form config data - :return: + Return without external I/O when the settings and tenant-owned extension exist. + Invalid settings or a missing extension raise ValueError; lookup errors propagate. """ cls._validate_inputs_and_outputs_config(config, False) @@ -41,8 +38,7 @@ def validate_config(cls, tenant_id: str, config: dict[str, Any]): if not api_based_extension_id: raise ValueError("api_based_extension_id is required") - extension = cls._get_api_based_extension(tenant_id, api_based_extension_id, db.session) - if not extension: + if cls._get_api_based_extension(tenant_id, api_based_extension_id) is None: raise ValueError("API-based Extension not found. Please check it again.") @override @@ -79,26 +75,39 @@ def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: flagged=flagged, action=ModerationAction.DIRECT_OUTPUT, preset_response=preset_response ) - def _get_config_by_requestor(self, extension_point: APIBasedExtensionPoint, params: dict[str, Any]): + def _get_config_by_requestor( + self, extension_point: APIBasedExtensionPoint, params: dict[str, Any] + ) -> dict[str, object]: + """Request moderation from the configured extension after releasing the lookup session. + + Return the extension response for the supplied point and parameters. + Missing config or a missing tenant-owned extension raises ValueError; lookup, + decryption, and request failures propagate unchanged. + """ if self.config is None: raise ValueError("The config is not set.") - extension = self._get_api_based_extension( - self.tenant_id, self.config.get("api_based_extension_id", ""), db.session - ) - if not extension: + extension = self._get_api_based_extension(self.tenant_id, self.config.get("api_based_extension_id", "")) + if extension is None: raise ValueError("API-based Extension not found. Please check it again.") - requestor = APIBasedExtensionRequestor(extension.api_endpoint, decrypt_token(self.tenant_id, extension.api_key)) + endpoint, encrypted_key = extension + requestor = APIBasedExtensionRequestor(endpoint, decrypt_token(self.tenant_id, encrypted_key)) result = requestor.request(extension_point, params) return result @staticmethod - def _get_api_based_extension( - tenant_id: str, api_based_extension_id: str, session: scoped_session - ) -> APIBasedExtension | None: - stmt = select(APIBasedExtension).where( + def _get_api_based_extension(tenant_id: str, api_based_extension_id: str) -> tuple[str, str] | None: + """Read the tenant's endpoint and encrypted key using the configured session factory. + + Return None if the extension is absent. Close the owned session before returning + or propagating a lookup error. + """ + stmt = select(APIBasedExtension.api_endpoint, APIBasedExtension.api_key).where( APIBasedExtension.tenant_id == tenant_id, APIBasedExtension.id == api_based_extension_id ) - extension = session.scalar(stmt) - - return extension + with session_factory.create_session() as session: + row = session.execute(stmt).tuples().one_or_none() + if row is None: + return None + endpoint, encrypted_key = row + return endpoint, encrypted_key diff --git a/api/tests/unit_tests/core/moderation/api/test_api.py b/api/tests/unit_tests/core/moderation/api/test_api.py index 97a4ba25af36a5..d1073fbb8a33e7 100644 --- a/api/tests/unit_tests/core/moderation/api/test_api.py +++ b/api/tests/unit_tests/core/moderation/api/test_api.py @@ -1,19 +1,29 @@ -from unittest.mock import MagicMock, patch +import re +from collections.abc import Iterator import pytest from pydantic import ValidationError -from sqlalchemy.orm import Session +from sqlalchemy import Engine, event +from sqlalchemy.orm import Session, sessionmaker -from core.extension.api_based_extension_requestor import APIBasedExtensionPoint +from core.extension.api_based_extension_requestor import APIBasedExtensionRequestor from core.moderation.api.api import ApiModeration, ModerationInputParams, ModerationOutputParams from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult -from extensions.ext_database import db -from models.api_based_extension import APIBasedExtension +from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint + +_EXTENSION_ID = "a0000000-0000-0000-0000-000000000001" +_FOREIGN_EXTENSION_ID = "a0000000-0000-0000-0000-000000000002" +_MISSING_EXTENSION_ID = "a0000000-0000-0000-0000-000000000003" +_TENANT_ID = "a0000000-0000-0000-0000-000000000004" +_FOREIGN_TENANT_ID = "a0000000-0000-0000-0000-000000000005" +_ENDPOINT = "https://moderation.example.test/check" +_EXTENSION_NOT_FOUND = r"^API-based Extension not found\. Please check it again\.$" class TestApiModeration: @pytest.fixture def api_config(self) -> dict[str, object]: + """Return enabled input/output settings for the seeded tenant-owned extension.""" return { "inputs_config": { "enabled": True, @@ -21,12 +31,56 @@ def api_config(self) -> dict[str, object]: "outputs_config": { "enabled": True, }, - "api_based_extension_id": "test-extension-id", + "api_based_extension_id": _EXTENSION_ID, } @pytest.fixture - def api_moderation(self, api_config: dict[str, object]) -> ApiModeration: - return ApiModeration(app_id="test-app-id", tenant_id="test-tenant-id", config=api_config) + def lookup_events( + self, sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session] + ) -> Iterator[list[str]]: + """Observe pool activity after committing the owner and foreign extension rows.""" + target = APIBasedExtension( + tenant_id=_TENANT_ID, name="Target extension", api_endpoint=_ENDPOINT, api_key="encrypted-key" + ) + target.id = _EXTENSION_ID + foreign = APIBasedExtension( + tenant_id=_FOREIGN_TENANT_ID, + name="Foreign extension", + api_endpoint="https://moderation.example.test/foreign", + api_key="foreign-key", + ) + foreign.id = _FOREIGN_EXTENSION_ID + with sqlite_session_factory.begin() as session: + session.add_all((target, foreign)) + + events: list[str] = [] + + def checkout(*_args: object) -> None: + """Record that the lookup acquired a real pooled connection.""" + events.append("checkout") + + def checkin(*_args: object) -> None: + """Record that the lookup returned its pooled connection.""" + events.append("checkin") + + event.listen(sqlite_engine, "checkout", checkout) + event.listen(sqlite_engine, "checkin", checkin) + try: + yield events + finally: + event.remove(sqlite_engine, "checkout", checkout) + event.remove(sqlite_engine, "checkin", checkin) + + @pytest.fixture + def no_external_calls(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Fail if moderation attempts decryption or dispatches an extension request.""" + + def unexpected_call(*_args: object, **_kwargs: object) -> None: + """Fail if a guarded path decrypts or dispatches an extension request.""" + pytest.fail("Unexpected decryption or extension request") + + monkeypatch.setattr("core.moderation.api.api.decrypt_token", unexpected_call) + monkeypatch.setattr(APIBasedExtensionRequestor, "request", unexpected_call) def test_moderation_input_params(self) -> None: params = ModerationInputParams(app_id="app-1", inputs={"key": "val"}, query="test query") @@ -41,169 +95,188 @@ def test_moderation_input_params(self) -> None: assert params_default.query == "" def test_moderation_output_params(self) -> None: + """Validate output parameter values and reject a missing required text field.""" params = ModerationOutputParams(app_id="app-1", text="test text") assert params.app_id == "app-1" assert params.text == "test text" with pytest.raises(ValidationError): - ModerationOutputParams() # pyrefly: ignore[missing-argument] - - @patch("core.moderation.api.api.ApiModeration._get_api_based_extension") - def test_validate_config_success(self, mock_get_extension: MagicMock, api_config: dict[str, object]) -> None: - mock_get_extension.return_value = APIBasedExtension( - tenant_id="tenant-id", name="Test Extension", api_endpoint="https://example.com", api_key="test-key" - ) - ApiModeration.validate_config("test-tenant-id", api_config) - mock_get_extension.assert_called_once_with("test-tenant-id", "test-extension-id", db.session) + ModerationOutputParams.model_validate({}) + + @pytest.mark.usefixtures("no_external_calls") + def test_validate_config_success(self, api_config: dict[str, object], lookup_events: list[str]) -> None: + """Accept the seeded owned extension and release the read without external I/O.""" + ApiModeration.validate_config(_TENANT_ID, api_config) + + assert lookup_events == ["checkout", "checkin"] + + @pytest.mark.parametrize( + ("config", "message"), + [ + ( + {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, + "At least one of inputs_config or outputs_config must be enabled", + ), + ( + {"inputs_config": {"enabled": True}, "outputs_config": {"enabled": True}}, + "api_based_extension_id is required", + ), + ], + ) + @pytest.mark.usefixtures("no_external_calls") + def test_validate_config_rejects_invalid_config_before_lookup( + self, config: dict[str, object], message: str, lookup_events: list[str] + ) -> None: + """Reject invalid settings in the existing order without opening a connection.""" + with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): + ApiModeration.validate_config(_TENANT_ID, config) - def test_validate_config_missing_extension_id(self) -> None: - config = { - "inputs_config": {"enabled": True}, - "outputs_config": {"enabled": True}, - } - with pytest.raises(ValueError, match="api_based_extension_id is required"): - ApiModeration.validate_config("test-tenant-id", config) + assert lookup_events == [] - @patch("core.moderation.api.api.ApiModeration._get_api_based_extension") + @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) + @pytest.mark.usefixtures("no_external_calls") def test_validate_config_extension_not_found( - self, mock_get_extension: MagicMock, api_config: dict[str, object] + self, extension_id: str, api_config: dict[str, object], lookup_events: list[str] ) -> None: - mock_get_extension.return_value = None - with pytest.raises(ValueError, match="API-based Extension not found"): - ApiModeration.validate_config("test-tenant-id", api_config) - - @patch("core.moderation.api.api.ApiModeration._get_config_by_requestor") - def test_moderation_for_inputs_enabled(self, mock_get_config: MagicMock, api_moderation: ApiModeration) -> None: - mock_get_config.return_value = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} - - result = api_moderation.moderation_for_inputs(inputs={"q": "a"}, query="hello") + """Reject missing or foreign extensions and release the lookup connection.""" + api_config["api_based_extension_id"] = extension_id - assert isinstance(result, ModerationInputsResult) - assert result.flagged is True - assert result.action == ModerationAction.DIRECT_OUTPUT - assert result.preset_response == "Blocked by API" - - mock_get_config.assert_called_once_with( - APIBasedExtensionPoint.APP_MODERATION_INPUT, - {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"}, - ) + with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): + ApiModeration.validate_config(_TENANT_ID, api_config) - def test_moderation_for_inputs_disabled(self) -> None: - config = { - "inputs_config": {"enabled": False}, - "outputs_config": {"enabled": True}, - "api_based_extension_id": "ext-id", - } - moderation = ApiModeration("app-id", "tenant-id", config) - result = moderation.moderation_for_inputs(inputs={}, query="") + assert lookup_events == ["checkout", "checkin"] - assert result.flagged is False - assert result.action == ModerationAction.DIRECT_OUTPUT - assert result.preset_response == "" + @pytest.mark.parametrize("direction", ["inputs", "outputs"]) + def test_enabled_moderation_releases_connection_before_external_io( + self, + direction: str, + api_config: dict[str, object], + lookup_events: list[str], + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Preserve the selected request and result after returning the lookup connection.""" + moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) + response: dict[str, object] + if direction == "inputs": + point = APIBasedExtensionPoint.APP_MODERATION_INPUT + params = {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"} + response = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} + expected = ModerationInputsResult( + flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked by API" + ) + else: + point = APIBasedExtensionPoint.APP_MODERATION_OUTPUT + params = {"app_id": "test-app-id", "text": "hello world"} + response = {"flagged": False, "action": "direct_output", "preset_response": ""} + expected = ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + + def decrypt(tenant_id: str, encrypted_key: str) -> str: + """Check the tenant and ciphertext after lookup release, then supply the test key.""" + assert lookup_events == ["checkout", "checkin"] + assert (tenant_id, encrypted_key) == (_TENANT_ID, "encrypted-key") + lookup_events.append("decrypt") + return "decrypted-key" + + def request( + requestor: APIBasedExtensionRequestor, + actual_point: APIBasedExtensionPoint, + actual_params: dict[str, object], + ) -> dict[str, object]: + """Check the constructed requestor and dispatch arguments after lookup release.""" + assert lookup_events == ["checkout", "checkin", "decrypt"] + assert requestor.api_endpoint == _ENDPOINT + assert requestor.api_key == "decrypted-key" + assert actual_point is point + assert actual_params == params + lookup_events.append("request") + return response + + monkeypatch.setattr("core.moderation.api.api.decrypt_token", decrypt) + monkeypatch.setattr(APIBasedExtensionRequestor, "request", request) + + assert _moderate(moderation, direction) == expected + assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + + @pytest.mark.parametrize("direction", ["inputs", "outputs"]) + @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID, None]) + @pytest.mark.usefixtures("no_external_calls") + def test_enabled_moderation_extension_not_found( + self, direction: str, extension_id: str | None, api_config: dict[str, object], lookup_events: list[str] + ) -> None: + """Reject absent or foreign runtime extensions without external I/O.""" + if extension_id is None: + del api_config["api_based_extension_id"] + else: + api_config["api_based_extension_id"] = extension_id + moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) + + with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): + _moderate(moderation, direction) + + assert lookup_events == ["checkout", "checkin"] + + @pytest.mark.parametrize("direction", ["inputs", "outputs"]) + @pytest.mark.usefixtures("no_external_calls") + def test_disabled_moderation_skips_lookup( + self, direction: str, api_config: dict[str, object], lookup_events: list[str] + ) -> None: + """Return the disabled result without database or external I/O.""" + api_config[f"{direction}_config"] = {"enabled": False} + moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) - def test_moderation_for_inputs_no_config(self) -> None: - moderation = ApiModeration("app-id", "tenant-id", None) - with pytest.raises(ValueError, match="The config is not set"): - moderation.moderation_for_inputs({}, "") + result = _moderate(moderation, direction) + if direction == "inputs": + assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + else: + assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) - @patch("core.moderation.api.api.ApiModeration._get_config_by_requestor") - def test_moderation_for_outputs_enabled(self, mock_get_config: MagicMock, api_moderation: ApiModeration) -> None: - mock_get_config.return_value = {"flagged": False, "action": "direct_output", "preset_response": ""} + assert lookup_events == [] - result = api_moderation.moderation_for_outputs(text="hello world") + @pytest.mark.parametrize("direction", ["inputs", "outputs"]) + @pytest.mark.usefixtures("no_external_calls") + def test_moderation_without_config_skips_lookup(self, direction: str, lookup_events: list[str]) -> None: + """Reject absent runtime config before database or external I/O.""" + moderation = ApiModeration("test-app-id", _TENANT_ID, None) - assert isinstance(result, ModerationOutputsResult) - assert result.flagged is False + with pytest.raises(ValueError, match=r"^The config is not set\.$"): + _moderate(moderation, direction) - mock_get_config.assert_called_once_with( - APIBasedExtensionPoint.APP_MODERATION_OUTPUT, {"app_id": "test-app-id", "text": "hello world"} - ) + assert lookup_events == [] - def test_moderation_for_outputs_disabled(self) -> None: - config = { - "inputs_config": {"enabled": True}, - "outputs_config": {"enabled": False}, - "api_based_extension_id": "ext-id", - } - moderation = ApiModeration("app-id", "tenant-id", config) - result = moderation.moderation_for_outputs(text="test") + @pytest.mark.usefixtures("no_external_calls") + def test_get_config_by_requestor_no_config(self, lookup_events: list[str]) -> None: + """Reject absent config in the private request helper without I/O.""" + moderation = ApiModeration("test-app-id", _TENANT_ID, None) - assert result.flagged is False - assert result.action == ModerationAction.DIRECT_OUTPUT + with pytest.raises(ValueError, match=r"^The config is not set\.$"): + moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}) - def test_moderation_for_outputs_no_config(self) -> None: - moderation = ApiModeration("app-id", "tenant-id", None) - with pytest.raises(ValueError, match="The config is not set"): - moderation.moderation_for_outputs("test") + assert lookup_events == [] - @patch("core.moderation.api.api.ApiModeration._get_api_based_extension") - @patch("core.moderation.api.api.decrypt_token") - @patch("core.moderation.api.api.APIBasedExtensionRequestor") - def test_get_config_by_requestor_success( - self, - mock_requestor_cls: MagicMock, - mock_decrypt: MagicMock, - mock_get_ext: MagicMock, - api_moderation: ApiModeration, + @pytest.mark.usefixtures("no_external_calls") + def test_lookup_failure_releases_connection( + self, api_config: dict[str, object], lookup_events: list[str], sqlite_engine: Engine ) -> None: - mock_ext = APIBasedExtension( - tenant_id="tenant-id", - name="Test Extension", - api_endpoint="http://api.test", - api_key="encrypted-key", - ) - mock_get_ext.return_value = mock_ext + """Propagate the original query failure after returning its connection.""" + failure = RuntimeError("lookup failed") - mock_decrypt.return_value = "decrypted-key" + def fail_query(*_args: object) -> None: + """Raise the test failure after the real connection has been checked out.""" + raise failure - mock_requestor = MagicMock() - mock_requestor.request.return_value = {"flagged": True} - mock_requestor_cls.return_value = mock_requestor + event.listen(sqlite_engine, "before_cursor_execute", fail_query) + try: + with pytest.raises(RuntimeError) as exc_info: + ApiModeration("test-app-id", _TENANT_ID, api_config).moderation_for_outputs("test") + finally: + event.remove(sqlite_engine, "before_cursor_execute", fail_query) - params = {"some": "params"} - result = api_moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, params) + assert exc_info.value is failure + assert lookup_events == ["checkout", "checkin"] - assert result == {"flagged": True} - mock_get_ext.assert_called_once_with("test-tenant-id", "test-extension-id", db.session) - mock_decrypt.assert_called_once_with("test-tenant-id", "encrypted-key") - mock_requestor_cls.assert_called_once_with("http://api.test", "decrypted-key") - mock_requestor.request.assert_called_once_with(APIBasedExtensionPoint.APP_MODERATION_INPUT, params) - def test_get_config_by_requestor_no_config(self) -> None: - moderation = ApiModeration("app-id", "tenant-id", None) - with pytest.raises(ValueError, match="The config is not set"): - moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}) - - @patch("core.moderation.api.api.ApiModeration._get_api_based_extension") - def test_get_config_by_requestor_extension_not_found( - self, mock_get_ext: MagicMock, api_moderation: ApiModeration - ) -> None: - mock_get_ext.return_value = None - with pytest.raises(ValueError, match="API-based Extension not found"): - api_moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}) - - def test_get_api_based_extension(self, sqlite_session: Session) -> None: - target = APIBasedExtension( - tenant_id="tenant-1", - name="Target extension", - api_endpoint="https://example.com/moderate", - api_key="encrypted-key", - ) - target.id = "ext-1" - other_tenant = APIBasedExtension( - tenant_id="tenant-2", - name="Other extension", - api_endpoint="https://example.com/other", - api_key="other-key", - ) - other_tenant.id = "ext-2" - sqlite_session.add_all((target, other_tenant)) - sqlite_session.commit() - - result = ApiModeration._get_api_based_extension("tenant-1", "ext-1", sqlite_session) # pyrefly: ignore[bad-argument-type] - - assert result is target - assert ( - ApiModeration._get_api_based_extension("tenant-1", "ext-2", sqlite_session) # pyrefly: ignore[bad-argument-type] - is None - ) +def _moderate(moderation: ApiModeration, direction: str) -> ModerationInputsResult | ModerationOutputsResult: + """Call the selected public moderation entry point with sample content.""" + if direction == "inputs": + return moderation.moderation_for_inputs({"q": "a"}, "hello") + return moderation.moderation_for_outputs("hello world") From 03fa44c44a6a2e7d46c9f21d7b52d52529800466 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Mon, 9 Nov 2026 15:33:31 +0800 Subject: [PATCH 02/12] chore(ci): retry checks after model download timeout From 6745a908f851337000ad4d7de242d36a52af6c2e Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Mon, 9 Nov 2026 19:16:46 +0800 Subject: [PATCH 03/12] test(api): keep EPUB spine fixture independent of NLP downloads --- api/tests/unit_tests/libs/test_epub.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/api/tests/unit_tests/libs/test_epub.py b/api/tests/unit_tests/libs/test_epub.py index 4f657bc5641397..a69746a2bf47c1 100644 --- a/api/tests/unit_tests/libs/test_epub.py +++ b/api/tests/unit_tests/libs/test_epub.py @@ -24,12 +24,14 @@ def test_partition_epub_preserves_spine_order_and_title_chunking(tmp_path: Path) '' '', ) - archive.writestr("OPS/nav.xhtml", "

Navigation only

") + # Explicit HTML element types avoid downloading an NLP model to classify text. + archive.writestr("OPS/nav.xhtml", "

Navigation only

") archive.writestr( - "OPS/Text/second.xhtml", "

Second chapter

Second body.

" + "OPS/Text/second.xhtml", "

Second chapter

  • Second body.
" ) archive.writestr( - "OPS/Text/first chapter.xhtml", "

First chapter

First body.

" + "OPS/Text/first chapter.xhtml", + "

First chapter

  • First body.
", ) elements = partition_epub(str(file_path)) From 6d229e6ef8adac1ab472ebdaf3fe186cb8b5b7ba Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 10:57:17 +0800 Subject: [PATCH 04/12] refactor(api): inject moderation application dependencies --- api/.importlinter | 35 ++ api/core/moderation/api/__builtin__ | 1 - api/core/moderation/api/__init__.py | 0 api/core/moderation/api/api.py | 113 ------ api/core/moderation/factory.py | 89 ++++- api/extensions/ext_application_services.py | 28 +- .../api_based_extension_repository.py | 4 +- api/services/api_based_extension_adapters.py | 24 ++ api/services/api_moderation_service.py | 154 ++++++++ .../core/moderation/api/test_api.py | 282 -------------- .../test_openai_moderation.py | 40 -- .../core/moderation/test_factory.py | 205 ++++++++++ .../test_ext_application_services.py | 41 ++ .../test_api_based_extension_adapters.py | 43 ++- .../services/test_api_moderation_service.py | 359 ++++++++++++++++++ .../test_code_based_extension_service.py | 6 + 16 files changed, 973 insertions(+), 451 deletions(-) delete mode 100644 api/core/moderation/api/__builtin__ delete mode 100644 api/core/moderation/api/__init__.py delete mode 100644 api/core/moderation/api/api.py create mode 100644 api/services/api_moderation_service.py delete mode 100644 api/tests/unit_tests/core/moderation/api/test_api.py create mode 100644 api/tests/unit_tests/core/moderation/test_factory.py create mode 100644 api/tests/unit_tests/services/test_api_moderation_service.py diff --git a/api/.importlinter b/api/.importlinter index 6c9c709ea737f8..32ac793260622f 100644 --- a/api/.importlinter +++ b/api/.importlinter @@ -945,6 +945,41 @@ forbidden_modules = sqlalchemy werkzeug +[importlinter:contract:api-moderation-application-boundary] +name = API moderation owns framework-neutral parsing and orchestration +type = forbidden +source_modules = + services.api_moderation_service +forbidden_modules = + celery + configs + controllers + core + extensions + flask + models + repositories + sqlalchemy + tasks + werkzeug + services.api_based_extension_adapters + +[importlinter:contract:moderation-factory-boundary] +name = Moderation factory uses root-bound callbacks instead of persistence or application imports +type = forbidden +source_modules = + core.moderation.factory +forbidden_modules = + core.db + core.helper.encrypter + core.extension.api_based_extension_requestor + extensions.ext_application_services + models + repositories + services + sqlalchemy +allow_indirect_imports = True + [importlinter:contract:console-extension-controller-boundary] name = Console extension controller reaches persistence only through the composition root type = forbidden diff --git a/api/core/moderation/api/__builtin__ b/api/core/moderation/api/__builtin__ deleted file mode 100644 index 00750edc07d641..00000000000000 --- a/api/core/moderation/api/__builtin__ +++ /dev/null @@ -1 +0,0 @@ -3 diff --git a/api/core/moderation/api/__init__.py b/api/core/moderation/api/__init__.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/api/core/moderation/api/api.py b/api/core/moderation/api/api.py deleted file mode 100644 index b199baa76c8027..00000000000000 --- a/api/core/moderation/api/api.py +++ /dev/null @@ -1,113 +0,0 @@ -from typing import Any, override - -from pydantic import BaseModel, Field -from sqlalchemy import select - -from core.db.session_factory import session_factory -from core.extension.api_based_extension_requestor import APIBasedExtensionPoint, APIBasedExtensionRequestor -from core.helper.encrypter import decrypt_token -from core.moderation.base import Moderation, ModerationAction, ModerationInputsResult, ModerationOutputsResult -from models.api_based_extension import APIBasedExtension - - -class ModerationInputParams(BaseModel): - app_id: str = "" - inputs: dict[str, Any] = Field(default_factory=dict) - query: str = "" - - -class ModerationOutputParams(BaseModel): - app_id: str = "" - text: str - - -class ApiModeration(Moderation): - name: str = "api" - - @classmethod - @override - def validate_config(cls, tenant_id: str, config: dict[str, Any]) -> None: - """Validate form settings and require an extension owned by the workspace. - - Return without external I/O when the settings and tenant-owned extension exist. - Invalid settings or a missing extension raise ValueError; lookup errors propagate. - """ - cls._validate_inputs_and_outputs_config(config, False) - - api_based_extension_id = config.get("api_based_extension_id") - if not api_based_extension_id: - raise ValueError("api_based_extension_id is required") - - if cls._get_api_based_extension(tenant_id, api_based_extension_id) is None: - raise ValueError("API-based Extension not found. Please check it again.") - - @override - def moderation_for_inputs(self, inputs: dict[str, Any], query: str = "") -> ModerationInputsResult: - flagged = False - preset_response = "" - if self.config is None: - raise ValueError("The config is not set.") - - if self.config["inputs_config"]["enabled"]: - params = ModerationInputParams(app_id=self.app_id, inputs=inputs, query=query) - - result = self._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, params.model_dump()) - return ModerationInputsResult.model_validate(result) - - return ModerationInputsResult( - flagged=flagged, action=ModerationAction.DIRECT_OUTPUT, preset_response=preset_response - ) - - @override - def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: - flagged = False - preset_response = "" - if self.config is None: - raise ValueError("The config is not set.") - - if self.config["outputs_config"]["enabled"]: - params = ModerationOutputParams(app_id=self.app_id, text=text) - - result = self._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_OUTPUT, params.model_dump()) - return ModerationOutputsResult.model_validate(result) - - return ModerationOutputsResult( - flagged=flagged, action=ModerationAction.DIRECT_OUTPUT, preset_response=preset_response - ) - - def _get_config_by_requestor( - self, extension_point: APIBasedExtensionPoint, params: dict[str, Any] - ) -> dict[str, object]: - """Request moderation from the configured extension after releasing the lookup session. - - Return the extension response for the supplied point and parameters. - Missing config or a missing tenant-owned extension raises ValueError; lookup, - decryption, and request failures propagate unchanged. - """ - if self.config is None: - raise ValueError("The config is not set.") - extension = self._get_api_based_extension(self.tenant_id, self.config.get("api_based_extension_id", "")) - if extension is None: - raise ValueError("API-based Extension not found. Please check it again.") - endpoint, encrypted_key = extension - requestor = APIBasedExtensionRequestor(endpoint, decrypt_token(self.tenant_id, encrypted_key)) - - result = requestor.request(extension_point, params) - return result - - @staticmethod - def _get_api_based_extension(tenant_id: str, api_based_extension_id: str) -> tuple[str, str] | None: - """Read the tenant's endpoint and encrypted key using the configured session factory. - - Return None if the extension is absent. Close the owned session before returning - or propagating a lookup error. - """ - stmt = select(APIBasedExtension.api_endpoint, APIBasedExtension.api_key).where( - APIBasedExtension.tenant_id == tenant_id, APIBasedExtension.id == api_based_extension_id - ) - with session_factory.create_session() as session: - row = session.execute(stmt).tuples().one_or_none() - if row is None: - return None - endpoint, encrypted_key = row - return endpoint, encrypted_key diff --git a/api/core/moderation/factory.py b/api/core/moderation/factory.py index c22306ac94ec7e..df9d5be7a22897 100644 --- a/api/core/moderation/factory.py +++ b/api/core/moderation/factory.py @@ -1,30 +1,81 @@ +from collections.abc import Callable, Mapping +from dataclasses import dataclass from typing import Any +from flask import current_app + from core.extension.extensible import ExtensionModule from core.moderation.base import Moderation, ModerationInputsResult, ModerationOutputsResult from extensions.ext_code_based_extension import code_based_extension +API_MODERATION_EXTENSION_KEY = "api_moderation" + + +@dataclass(frozen=True, slots=True) +class APIModerationCallbacks: + """Required API capabilities bound by the composition root to one Flask app.""" + + validate_config: Callable[[str, Mapping[str, object]], None] + moderate_inputs: Callable[[str, str, Mapping[str, object] | None, dict[str, object], str], object] + moderate_outputs: Callable[[str, str, Mapping[str, object] | None, str], object] + + +@dataclass(slots=True) +class _APIModeration: + """Raw settings remain unparsed until the selected operation runs. + + Callbacks are cached by the first operation, so construction needs no Flask context. + """ + + app_id: str + tenant_id: str + config: Mapping[str, object] | None + callbacks: APIModerationCallbacks | None = None + + +def _api_callbacks() -> APIModerationCallbacks: + """Require the current app's root-bound bundle without importing its services.""" + callbacks = current_app.extensions[API_MODERATION_EXTENSION_KEY] + if not isinstance(callbacks, APIModerationCallbacks): + raise TypeError("API moderation callbacks are not configured") + return callbacks + + +def _moderation_class(name: str) -> type[Moderation]: + """Resolve a scanned provider and require the existing moderation contract.""" + extension_class = code_based_extension.extension_class(ExtensionModule.MODERATION, name) + if not issubclass(extension_class, Moderation): + raise TypeError(f"Extension {name} is not a moderation provider") + return extension_class + class ModerationFactory: - __extension_instance: Moderation + __extension_instance: Moderation | _APIModeration - def __init__(self, name: str, app_id: str, tenant_id: str, config: dict[str, Any]): - extension_class = code_based_extension.extension_class(ExtensionModule.MODERATION, name) - self.__extension_instance = extension_class(app_id, tenant_id, config) + def __init__(self, name: str, app_id: str, tenant_id: str, config: dict[str, Any] | None): + """Accept raw settings without I/O; API service binding waits for an operation.""" + if name == "api": + self.__extension_instance = _APIModeration(app_id, tenant_id, config) + else: + self.__extension_instance = _moderation_class(name)(app_id, tenant_id, config) @classmethod def validate_config(cls, name: str, tenant_id: str, config: dict[str, Any]): """ Validate the incoming form config data. + API validation requires an initialized Flask app context. Binding and + service failures propagate without changing settings or making outbound calls. + :param name: the name of extension :param tenant_id: the id of workspace :param config: the form config data :return: """ - extension_class = code_based_extension.extension_class(ExtensionModule.MODERATION, name) - # FIXME: mypy error, try to fix it instead of using type: ignore - extension_class.validate_config(tenant_id, config) # type: ignore + if name == "api": + _api_callbacks().validate_config(tenant_id, config) + else: + _moderation_class(name).validate_config(tenant_id, config) def moderation_for_inputs(self, inputs: dict[str, Any], query: str = "") -> ModerationInputsResult: """ @@ -32,11 +83,22 @@ def moderation_for_inputs(self, inputs: dict[str, Any], query: str = "") -> Mode After the user inputs, this method will be called to perform sensitive content review on the user inputs and return the processed results. + The first API operation requires an initialized Flask app context. + Binding, service, and response-validation failures propagate unchanged. + :param inputs: user inputs :param query: query string (required in chat app) :return: """ - return self.__extension_instance.moderation_for_inputs(inputs, query) + provider = self.__extension_instance + if isinstance(provider, _APIModeration): + if provider.callbacks is None: + provider.callbacks = _api_callbacks() + result = provider.callbacks.moderate_inputs( + provider.tenant_id, provider.app_id, provider.config, inputs, query + ) + return ModerationInputsResult.model_validate(result) + return provider.moderation_for_inputs(inputs, query) def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: """ @@ -44,7 +106,16 @@ def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: When LLM outputs content, the front end will pass the output content (may be segmented) to this method for sensitive content review, and the output content will be shielded if the review fails. + The first API operation requires an initialized Flask app context. + Binding, service, and response-validation failures propagate unchanged. + :param text: LLM output content :return: """ - return self.__extension_instance.moderation_for_outputs(text) + provider = self.__extension_instance + if isinstance(provider, _APIModeration): + if provider.callbacks is None: + provider.callbacks = _api_callbacks() + result = provider.callbacks.moderate_outputs(provider.tenant_id, provider.app_id, provider.config, text) + return ModerationOutputsResult.model_validate(result) + return provider.moderation_for_outputs(text) diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py index bc11796392220d..472a73cb4dde73 100644 --- a/api/extensions/ext_application_services.py +++ b/api/extensions/ext_application_services.py @@ -17,6 +17,7 @@ from configs import dify_config from constants.dsl_version import CURRENT_APP_DSL_VERSION from core.db.session_factory import get_session_maker +from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks from core.schemas.schema_manager import SchemaManager from core.tools.tool_file_manager import ToolFileManager from core.tools.tool_manager import ToolManager @@ -115,8 +116,14 @@ from services.annotation_import_service import AnnotationImportLimits, AnnotationImportQuota, AnnotationImportService from services.annotation_query import AnnotationQuery from services.annotation_reply_service import AnnotationReplyService -from services.api_based_extension_adapters import APIBasedExtensionPingProbe, WorkspaceTokenCipher +from services.api_based_extension_adapters import ( + APIBasedExtensionPingProbe, + APIModerationGateway, + WorkspaceTokenCipher, + request_api_based_extension, +) from services.api_based_extension_application_service import APIBasedExtensionApplicationService +from services.api_moderation_service import APIModerationService from services.app.advanced_prompt_template_service import AdvancedPromptTemplateService from services.app.api_key_service import AppApiKeyService from services.app.mcp_server_service import AppMCPServerService @@ -302,6 +309,7 @@ class ApplicationServices: agent_apps: AgentAppServices advanced_prompt_templates: AdvancedPromptTemplateService api_based_extensions: APIBasedExtensionApplicationService + api_moderation: APIModerationService credential_queries: CredentialQuery accounts: AccountServices app_api_keys: AppApiKeyService @@ -453,6 +461,9 @@ def build_application_services( initialization_password: str, redis: RedisClientWrapper, ) -> ApplicationServices: + api_based_extensions = APIBasedExtensionRepository(session_factory=database_client) + workspace_token_cipher = WorkspaceTokenCipher() + api_moderation_gateway = APIModerationGateway(request=request_api_based_extension) installation_state = InstallationStateRepository(session_factory=database_client) app_definition_repository = AppDefinitionQueryRepository(session_factory=database_client) app_definitions = AppDefinitionQueryService( @@ -860,10 +871,16 @@ def build_application_services( access_token_expire_minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES, ), api_based_extensions=APIBasedExtensionApplicationService( - extensions=APIBasedExtensionRepository(session_factory=database_client), - secrets=WorkspaceTokenCipher(), + extensions=api_based_extensions, + secrets=workspace_token_cipher, probe=APIBasedExtensionPingProbe(), ), + api_moderation=APIModerationService( + find_extension=api_based_extensions.find_extension, + decrypt_key=workspace_token_cipher.decrypt, + request_inputs=api_moderation_gateway.inputs, + request_outputs=api_moderation_gateway.outputs, + ), tags=tags, workflow_statistics=WorkflowStatisticQueryService( workflow_runs=DifyAPIRepositoryFactory.create_api_workflow_run_repository( @@ -890,6 +907,11 @@ def init_app(app: Flask) -> None: redis=redis_client, ) app.extensions[_EXTENSION_KEY] = services + app.extensions[API_MODERATION_EXTENSION_KEY] = APIModerationCallbacks( + validate_config=services.api_moderation.validate_config, + moderate_inputs=services.api_moderation.moderate_inputs, + moderate_outputs=services.api_moderation.moderate_outputs, + ) bind_tracing(app, scopes=StoredPolicyTraceScopes(services.tracing.scopes), hooks=services.tracing.hooks) bind_account_loader(app, services.accounts.identity.load_user) diff --git a/api/repositories/api_based_extension_repository.py b/api/repositories/api_based_extension_repository.py index c67652aecbffd6..d350dec47a4488 100644 --- a/api/repositories/api_based_extension_repository.py +++ b/api/repositories/api_based_extension_repository.py @@ -31,7 +31,7 @@ def list_extensions(self, workspace_id: str) -> tuple[APIBasedExtensionRecord, . ) @override - def find_extension(self, workspace_id: str, extension_id: str) -> APIBasedExtensionRecord | None: + def find_extension(self, workspace_id: str, extension_id: object) -> APIBasedExtensionRecord | None: with self._session_factory() as session: extension = self._find(session, workspace_id, extension_id) return self._to_record(extension) if extension is not None else None @@ -79,7 +79,7 @@ def delete_extension(self, workspace_id: str, extension_id: str) -> None: session.delete(self._require(session, workspace_id, extension_id)) @staticmethod - def _find(session: Session, workspace_id: str, extension_id: str) -> APIBasedExtension | None: + def _find(session: Session, workspace_id: str, extension_id: object) -> APIBasedExtension | None: return session.scalar( select(APIBasedExtension) .where(APIBasedExtension.tenant_id == workspace_id, APIBasedExtension.id == extension_id) diff --git a/api/services/api_based_extension_adapters.py b/api/services/api_based_extension_adapters.py index 866d09f026cdeb..148b6f98a7cdec 100644 --- a/api/services/api_based_extension_adapters.py +++ b/api/services/api_based_extension_adapters.py @@ -1,5 +1,6 @@ """Runtime adapters for the API-based extension application service.""" +from collections.abc import Callable from typing import override from core.extension.api_based_extension_requestor import APIBasedExtensionRequestor @@ -10,6 +11,29 @@ APIBasedExtensionEndpointProbe, APIBasedExtensionSecretCipher, ) +from services.api_moderation_service import ModerationInputParams, ModerationOutputParams + + +def request_api_based_extension( + endpoint: str, key: str, point: APIBasedExtensionPoint, params: dict[str, object] +) -> object: + """Return the original requestor response; preserve its SSRF policy and errors.""" + return APIBasedExtensionRequestor(endpoint, key).request(point, params) + + +class APIModerationGateway: + """Translate typed moderation parameters to the existing extension wire format.""" + + def __init__(self, *, request: Callable[[str, str, APIBasedExtensionPoint, dict[str, object]], object]) -> None: + self._request = request + + def inputs(self, endpoint: str, key: str, params: ModerationInputParams) -> object: + """Dispatch the input point with validated params; propagate request errors.""" + return self._request(endpoint, key, APIBasedExtensionPoint.APP_MODERATION_INPUT, params.model_dump()) + + def outputs(self, endpoint: str, key: str, params: ModerationOutputParams) -> object: + """Dispatch the output point with validated params; propagate request errors.""" + return self._request(endpoint, key, APIBasedExtensionPoint.APP_MODERATION_OUTPUT, params.model_dump()) class WorkspaceTokenCipher(APIBasedExtensionSecretCipher): diff --git a/api/services/api_moderation_service.py b/api/services/api_moderation_service.py new file mode 100644 index 00000000000000..34c4910594b7d1 --- /dev/null +++ b/api/services/api_moderation_service.py @@ -0,0 +1,154 @@ +"""API moderation with explicit, workspace-scoped persistence and outbound capabilities. + +Form settings and runtime direction selection have distinct legacy contracts. Parse +only the selected runtime direction, and finish request validation before any I/O. +""" + +import operator +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Literal, TypedDict + +from pydantic import BaseModel, Field + +from services.api_based_extension_application_service import APIBasedExtensionRecord + + +class APIModerationDirectionConfig(TypedDict, total=False): + """Legacy enabled values use Python truthiness without boolean coercion.""" + + enabled: object + + +class APIModerationConfig(TypedDict, total=False): + """Stored API settings; an absent runtime ID still reaches the scoped lookup.""" + + inputs_config: APIModerationDirectionConfig + outputs_config: APIModerationDirectionConfig + api_based_extension_id: object + + +class ModerationInputParams(BaseModel): + app_id: str = "" + inputs: dict[str, object] = Field(default_factory=dict) + query: str = "" + + +class ModerationOutputParams(BaseModel): + app_id: str = "" + text: str + + +@dataclass(frozen=True, slots=True) +class DisabledDirection: + """The selected direction requires no lookup or outbound work.""" + + +@dataclass(frozen=True, slots=True) +class EnabledDirection: + """The original lookup key, preserved without string conversion.""" + + extension_id: object + + +def parse_direction( + raw: Mapping[str, object] | None, direction: Literal["inputs_config", "outputs_config"] +) -> DisabledDirection | EnabledDirection: + """Parse one runtime direction without inspecting the opposite direction. + + Missing config raises the existing ValueError. Native indexing errors and + truthiness are retained for malformed selected values. This function does no I/O. + """ + if raw is None: + raise ValueError("The config is not set.") + enabled: object = operator.itemgetter("enabled")(operator.itemgetter(direction)(raw)) + if enabled: + return EnabledDirection(raw.get("api_based_extension_id", "")) + return DisabledDirection() + + +def _parse_form(raw: Mapping[str, object]) -> EnabledDirection: + """Parse form settings in their existing error order without any I/O.""" + inputs_config = raw.get("inputs_config") + if not isinstance(inputs_config, dict): + raise ValueError("inputs_config must be a dict") + outputs_config = raw.get("outputs_config") + if not isinstance(outputs_config, dict): + raise ValueError("outputs_config must be a dict") + if not inputs_config.get("enabled") and not outputs_config.get("enabled"): + raise ValueError("At least one of inputs_config or outputs_config must be enabled") + extension_id = raw.get("api_based_extension_id") + if not extension_id: + raise ValueError("api_based_extension_id is required") + return EnabledDirection(extension_id) + + +class APIModerationService: + """Own API settings and release persistence before decryption and requests. + + All capabilities are required. Lookup returns detached records and owns its + short read session, including failure cleanup. All dependency errors propagate. + """ + + def __init__( + self, + *, + find_extension: Callable[[str, object], APIBasedExtensionRecord | None], + decrypt_key: Callable[[str, str], str], + request_inputs: Callable[[str, str, ModerationInputParams], object], + request_outputs: Callable[[str, str, ModerationOutputParams], object], + ) -> None: + self._find_extension = find_extension + self._decrypt_key = decrypt_key + self._request_inputs = request_inputs + self._request_outputs = request_outputs + + def validate_config(self, tenant_id: str, raw: Mapping[str, object]) -> None: + """Require valid form settings and an owned extension without outbound I/O. + + Invalid settings or absence raise the existing ValueError; lookup failures + propagate after its session closes. Successful validation changes no state. + """ + self._require_extension(tenant_id, _parse_form(raw).extension_id) + + def moderate_inputs( + self, + tenant_id: str, + app_id: str, + raw: Mapping[str, object] | None, + inputs: dict[str, object], + query: str = "", + ) -> object: + """Return the disabled result or raw input response for facade validation. + + Parse the selected direction and validate request parameters before lookup. + Lookup, decrypt and request failures propagate unchanged in that order. + """ + selection = parse_direction(raw, "inputs_config") + if isinstance(selection, DisabledDirection): + return {"flagged": False, "action": "direct_output", "preset_response": ""} + params = ModerationInputParams(app_id=app_id, inputs=inputs, query=query) + extension = self._require_extension(tenant_id, selection.extension_id) + key = self._decrypt_key(tenant_id, extension.api_key) + return self._request_inputs(extension.api_endpoint, key, params) + + def moderate_outputs(self, tenant_id: str, app_id: str, raw: Mapping[str, object] | None, text: str) -> object: + """Return the disabled result or raw output response for facade validation. + + Parse the selected direction and validate request parameters before lookup. + Lookup, decrypt and request failures propagate unchanged in that order. + """ + selection = parse_direction(raw, "outputs_config") + if isinstance(selection, DisabledDirection): + return {"flagged": False, "action": "direct_output", "preset_response": ""} + params = ModerationOutputParams(app_id=app_id, text=text) + extension = self._require_extension(tenant_id, selection.extension_id) + key = self._decrypt_key(tenant_id, extension.api_key) + return self._request_outputs(extension.api_endpoint, key, params) + + def _require_extension(self, tenant_id: str, extension_id: object) -> APIBasedExtensionRecord: + """Return an owned detached record or fail after the lookup session closes.""" + extension = self._find_extension(tenant_id, extension_id) + if extension is None: + raise ValueError("API-based Extension not found. Please check it again.") + return extension diff --git a/api/tests/unit_tests/core/moderation/api/test_api.py b/api/tests/unit_tests/core/moderation/api/test_api.py deleted file mode 100644 index d1073fbb8a33e7..00000000000000 --- a/api/tests/unit_tests/core/moderation/api/test_api.py +++ /dev/null @@ -1,282 +0,0 @@ -import re -from collections.abc import Iterator - -import pytest -from pydantic import ValidationError -from sqlalchemy import Engine, event -from sqlalchemy.orm import Session, sessionmaker - -from core.extension.api_based_extension_requestor import APIBasedExtensionRequestor -from core.moderation.api.api import ApiModeration, ModerationInputParams, ModerationOutputParams -from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult -from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint - -_EXTENSION_ID = "a0000000-0000-0000-0000-000000000001" -_FOREIGN_EXTENSION_ID = "a0000000-0000-0000-0000-000000000002" -_MISSING_EXTENSION_ID = "a0000000-0000-0000-0000-000000000003" -_TENANT_ID = "a0000000-0000-0000-0000-000000000004" -_FOREIGN_TENANT_ID = "a0000000-0000-0000-0000-000000000005" -_ENDPOINT = "https://moderation.example.test/check" -_EXTENSION_NOT_FOUND = r"^API-based Extension not found\. Please check it again\.$" - - -class TestApiModeration: - @pytest.fixture - def api_config(self) -> dict[str, object]: - """Return enabled input/output settings for the seeded tenant-owned extension.""" - return { - "inputs_config": { - "enabled": True, - }, - "outputs_config": { - "enabled": True, - }, - "api_based_extension_id": _EXTENSION_ID, - } - - @pytest.fixture - def lookup_events( - self, sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session] - ) -> Iterator[list[str]]: - """Observe pool activity after committing the owner and foreign extension rows.""" - target = APIBasedExtension( - tenant_id=_TENANT_ID, name="Target extension", api_endpoint=_ENDPOINT, api_key="encrypted-key" - ) - target.id = _EXTENSION_ID - foreign = APIBasedExtension( - tenant_id=_FOREIGN_TENANT_ID, - name="Foreign extension", - api_endpoint="https://moderation.example.test/foreign", - api_key="foreign-key", - ) - foreign.id = _FOREIGN_EXTENSION_ID - with sqlite_session_factory.begin() as session: - session.add_all((target, foreign)) - - events: list[str] = [] - - def checkout(*_args: object) -> None: - """Record that the lookup acquired a real pooled connection.""" - events.append("checkout") - - def checkin(*_args: object) -> None: - """Record that the lookup returned its pooled connection.""" - events.append("checkin") - - event.listen(sqlite_engine, "checkout", checkout) - event.listen(sqlite_engine, "checkin", checkin) - try: - yield events - finally: - event.remove(sqlite_engine, "checkout", checkout) - event.remove(sqlite_engine, "checkin", checkin) - - @pytest.fixture - def no_external_calls(self, monkeypatch: pytest.MonkeyPatch) -> None: - """Fail if moderation attempts decryption or dispatches an extension request.""" - - def unexpected_call(*_args: object, **_kwargs: object) -> None: - """Fail if a guarded path decrypts or dispatches an extension request.""" - pytest.fail("Unexpected decryption or extension request") - - monkeypatch.setattr("core.moderation.api.api.decrypt_token", unexpected_call) - monkeypatch.setattr(APIBasedExtensionRequestor, "request", unexpected_call) - - def test_moderation_input_params(self) -> None: - params = ModerationInputParams(app_id="app-1", inputs={"key": "val"}, query="test query") - assert params.app_id == "app-1" - assert params.inputs == {"key": "val"} - assert params.query == "test query" - - # Test defaults - params_default = ModerationInputParams() - assert params_default.app_id == "" - assert params_default.inputs == {} - assert params_default.query == "" - - def test_moderation_output_params(self) -> None: - """Validate output parameter values and reject a missing required text field.""" - params = ModerationOutputParams(app_id="app-1", text="test text") - assert params.app_id == "app-1" - assert params.text == "test text" - - with pytest.raises(ValidationError): - ModerationOutputParams.model_validate({}) - - @pytest.mark.usefixtures("no_external_calls") - def test_validate_config_success(self, api_config: dict[str, object], lookup_events: list[str]) -> None: - """Accept the seeded owned extension and release the read without external I/O.""" - ApiModeration.validate_config(_TENANT_ID, api_config) - - assert lookup_events == ["checkout", "checkin"] - - @pytest.mark.parametrize( - ("config", "message"), - [ - ( - {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, - "At least one of inputs_config or outputs_config must be enabled", - ), - ( - {"inputs_config": {"enabled": True}, "outputs_config": {"enabled": True}}, - "api_based_extension_id is required", - ), - ], - ) - @pytest.mark.usefixtures("no_external_calls") - def test_validate_config_rejects_invalid_config_before_lookup( - self, config: dict[str, object], message: str, lookup_events: list[str] - ) -> None: - """Reject invalid settings in the existing order without opening a connection.""" - with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): - ApiModeration.validate_config(_TENANT_ID, config) - - assert lookup_events == [] - - @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) - @pytest.mark.usefixtures("no_external_calls") - def test_validate_config_extension_not_found( - self, extension_id: str, api_config: dict[str, object], lookup_events: list[str] - ) -> None: - """Reject missing or foreign extensions and release the lookup connection.""" - api_config["api_based_extension_id"] = extension_id - - with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): - ApiModeration.validate_config(_TENANT_ID, api_config) - - assert lookup_events == ["checkout", "checkin"] - - @pytest.mark.parametrize("direction", ["inputs", "outputs"]) - def test_enabled_moderation_releases_connection_before_external_io( - self, - direction: str, - api_config: dict[str, object], - lookup_events: list[str], - monkeypatch: pytest.MonkeyPatch, - ) -> None: - """Preserve the selected request and result after returning the lookup connection.""" - moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) - response: dict[str, object] - if direction == "inputs": - point = APIBasedExtensionPoint.APP_MODERATION_INPUT - params = {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"} - response = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} - expected = ModerationInputsResult( - flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked by API" - ) - else: - point = APIBasedExtensionPoint.APP_MODERATION_OUTPUT - params = {"app_id": "test-app-id", "text": "hello world"} - response = {"flagged": False, "action": "direct_output", "preset_response": ""} - expected = ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) - - def decrypt(tenant_id: str, encrypted_key: str) -> str: - """Check the tenant and ciphertext after lookup release, then supply the test key.""" - assert lookup_events == ["checkout", "checkin"] - assert (tenant_id, encrypted_key) == (_TENANT_ID, "encrypted-key") - lookup_events.append("decrypt") - return "decrypted-key" - - def request( - requestor: APIBasedExtensionRequestor, - actual_point: APIBasedExtensionPoint, - actual_params: dict[str, object], - ) -> dict[str, object]: - """Check the constructed requestor and dispatch arguments after lookup release.""" - assert lookup_events == ["checkout", "checkin", "decrypt"] - assert requestor.api_endpoint == _ENDPOINT - assert requestor.api_key == "decrypted-key" - assert actual_point is point - assert actual_params == params - lookup_events.append("request") - return response - - monkeypatch.setattr("core.moderation.api.api.decrypt_token", decrypt) - monkeypatch.setattr(APIBasedExtensionRequestor, "request", request) - - assert _moderate(moderation, direction) == expected - assert lookup_events == ["checkout", "checkin", "decrypt", "request"] - - @pytest.mark.parametrize("direction", ["inputs", "outputs"]) - @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID, None]) - @pytest.mark.usefixtures("no_external_calls") - def test_enabled_moderation_extension_not_found( - self, direction: str, extension_id: str | None, api_config: dict[str, object], lookup_events: list[str] - ) -> None: - """Reject absent or foreign runtime extensions without external I/O.""" - if extension_id is None: - del api_config["api_based_extension_id"] - else: - api_config["api_based_extension_id"] = extension_id - moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) - - with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): - _moderate(moderation, direction) - - assert lookup_events == ["checkout", "checkin"] - - @pytest.mark.parametrize("direction", ["inputs", "outputs"]) - @pytest.mark.usefixtures("no_external_calls") - def test_disabled_moderation_skips_lookup( - self, direction: str, api_config: dict[str, object], lookup_events: list[str] - ) -> None: - """Return the disabled result without database or external I/O.""" - api_config[f"{direction}_config"] = {"enabled": False} - moderation = ApiModeration("test-app-id", _TENANT_ID, api_config) - - result = _moderate(moderation, direction) - if direction == "inputs": - assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) - else: - assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) - - assert lookup_events == [] - - @pytest.mark.parametrize("direction", ["inputs", "outputs"]) - @pytest.mark.usefixtures("no_external_calls") - def test_moderation_without_config_skips_lookup(self, direction: str, lookup_events: list[str]) -> None: - """Reject absent runtime config before database or external I/O.""" - moderation = ApiModeration("test-app-id", _TENANT_ID, None) - - with pytest.raises(ValueError, match=r"^The config is not set\.$"): - _moderate(moderation, direction) - - assert lookup_events == [] - - @pytest.mark.usefixtures("no_external_calls") - def test_get_config_by_requestor_no_config(self, lookup_events: list[str]) -> None: - """Reject absent config in the private request helper without I/O.""" - moderation = ApiModeration("test-app-id", _TENANT_ID, None) - - with pytest.raises(ValueError, match=r"^The config is not set\.$"): - moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}) - - assert lookup_events == [] - - @pytest.mark.usefixtures("no_external_calls") - def test_lookup_failure_releases_connection( - self, api_config: dict[str, object], lookup_events: list[str], sqlite_engine: Engine - ) -> None: - """Propagate the original query failure after returning its connection.""" - failure = RuntimeError("lookup failed") - - def fail_query(*_args: object) -> None: - """Raise the test failure after the real connection has been checked out.""" - raise failure - - event.listen(sqlite_engine, "before_cursor_execute", fail_query) - try: - with pytest.raises(RuntimeError) as exc_info: - ApiModeration("test-app-id", _TENANT_ID, api_config).moderation_for_outputs("test") - finally: - event.remove(sqlite_engine, "before_cursor_execute", fail_query) - - assert exc_info.value is failure - assert lookup_events == ["checkout", "checkin"] - - -def _moderate(moderation: ApiModeration, direction: str) -> ModerationInputsResult | ModerationOutputsResult: - """Call the selected public moderation entry point with sample content.""" - if direction == "inputs": - return moderation.moderation_for_inputs({"q": "a"}, "hello") - return moderation.moderation_for_outputs("hello world") diff --git a/api/tests/unit_tests/core/moderation/openai_moderation/test_openai_moderation.py b/api/tests/unit_tests/core/moderation/openai_moderation/test_openai_moderation.py index 03e6736311cc86..85b2a391d1ae26 100644 --- a/api/tests/unit_tests/core/moderation/openai_moderation/test_openai_moderation.py +++ b/api/tests/unit_tests/core/moderation/openai_moderation/test_openai_moderation.py @@ -519,46 +519,6 @@ def test_moderation_rule_structure(self) -> None: assert rule.config["outputs_config"]["preset_response"] == "Blocked" -class TestModerationFactoryIntegration: - """Test suite for ModerationFactory integration.""" - - @patch("core.moderation.factory.code_based_extension", autospec=True) - def test_factory_delegates_to_extension(self, mock_extension: Mock) -> None: - """Test ModerationFactory delegates to extension system.""" - from core.moderation.factory import ModerationFactory - - mock_instance = MagicMock() - mock_instance.moderation_for_inputs.return_value = ModerationInputsResult( - flagged=False, - action=ModerationAction.DIRECT_OUTPUT, - ) - mock_class = MagicMock(return_value=mock_instance) - mock_extension.extension_class.return_value = mock_class - - factory = ModerationFactory( - name="keywords", - app_id="app", - tenant_id="tenant", - config={}, - ) - - result = factory.moderation_for_inputs({"field": "value"}, "query") - assert result.flagged is False - mock_instance.moderation_for_inputs.assert_called_once() - - @patch("core.moderation.factory.code_based_extension", autospec=True) - def test_factory_validate_config_delegates(self, mock_extension: Mock) -> None: - """Test ModerationFactory.validate_config delegates to extension.""" - from core.moderation.factory import ModerationFactory - - mock_class = MagicMock() - mock_extension.extension_class.return_value = mock_class - - ModerationFactory.validate_config("keywords", "tenant", {"test": "config"}) - - mock_class.validate_config.assert_called_once() - - class TestModerationBase: """Test suite for base moderation classes and enums.""" diff --git a/api/tests/unit_tests/core/moderation/test_factory.py b/api/tests/unit_tests/core/moderation/test_factory.py new file mode 100644 index 00000000000000..7af282adaa619c --- /dev/null +++ b/api/tests/unit_tests/core/moderation/test_factory.py @@ -0,0 +1,205 @@ +from collections.abc import Iterator + +import pytest +from flask import Flask +from pydantic import ValidationError +from sqlalchemy import Engine, event +from sqlalchemy.orm import Session, sessionmaker + +from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult +from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory +from extensions.ext_code_based_extension import code_based_extension +from models.api_based_extension import APIBasedExtension +from repositories.api_based_extension_repository import APIBasedExtensionRepository +from services.api_moderation_service import APIModerationService, ModerationInputParams, ModerationOutputParams + +_TENANT_ID = "a0000000-0000-0000-0000-000000000004" +_EXTENSION_ID = "a0000000-0000-0000-0000-000000000001" + + +class _Requests: + def __init__(self) -> None: + self.response: object = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} + self.calls: list[object] = [] + + def decrypt(self, tenant_id: str, value: str) -> str: + self.calls.append((tenant_id, value)) + return "plaintext" + + def inputs(self, endpoint: str, key: str, params: ModerationInputParams) -> object: + self.calls.append((endpoint, key, params)) + return self.response + + def outputs(self, endpoint: str, key: str, params: ModerationOutputParams) -> object: + self.calls.append((endpoint, key, params)) + return self.response + + +@pytest.fixture +def requests() -> _Requests: + return _Requests() + + +@pytest.fixture +def moderation_app(sqlite_session_factory: sessionmaker[Session], requests: _Requests) -> Flask: + extension = APIBasedExtension( + tenant_id=_TENANT_ID, + name="Owned extension", + api_endpoint="https://moderation.example.test/check", + api_key="encrypted-key", + ) + extension.id = _EXTENSION_ID + with sqlite_session_factory.begin() as session: + session.add(extension) + service = APIModerationService( + find_extension=APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension, + decrypt_key=requests.decrypt, + request_inputs=requests.inputs, + request_outputs=requests.outputs, + ) + app = Flask(__name__) + app.extensions[API_MODERATION_EXTENSION_KEY] = APIModerationCallbacks( + service.validate_config, service.moderate_inputs, service.moderate_outputs + ) + return app + + +@pytest.mark.parametrize("config", [None, {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}]) +def test_api_construction_needs_no_app_context_or_io(config: dict[str, object] | None, sqlite_engine: Engine) -> None: + events: list[str] = [] + + def checkout(*_args: object) -> None: + events.append("checkout") + + event.listen(sqlite_engine, "checkout", checkout) + try: + ModerationFactory("api", "app", _TENANT_ID, config) + finally: + event.remove(sqlite_engine, "checkout", checkout) + assert events == [] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_api_factory_adapts_response_with_existing_model( + moderation_app: Flask, direction: str, requests: _Requests +) -> None: + factory = ModerationFactory( + "api", + "test-app-id", + _TENANT_ID, + { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": True}, + "api_based_extension_id": _EXTENSION_ID, + }, + ) + with moderation_app.app_context(): + if direction == "inputs": + result = factory.moderation_for_inputs({"q": "a"}, "hello") + assert result == ModerationInputsResult( + flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked by API" + ) + else: + requests.response = {"flagged": False, "action": "direct_output", "preset_response": ""} + result = factory.moderation_for_outputs("hello world") + assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert requests.calls[0] == (_TENANT_ID, "encrypted-key") + assert len(requests.calls) == 2 + + +@pytest.mark.parametrize("response", [None, [], "invalid", {"action": "invalid"}]) +def test_api_factory_retains_external_response_validation( + moderation_app: Flask, requests: _Requests, response: object +) -> None: + requests.response = response + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory( + "api", "app", _TENANT_ID, {"inputs_config": {"enabled": True}, "api_based_extension_id": _EXTENSION_ID} + ).moderation_for_inputs({}) + + +def test_api_factory_binds_once_at_first_operation(moderation_app: Flask, requests: _Requests) -> None: + factory = ModerationFactory("api", "app", _TENANT_ID, {"inputs_config": {"enabled": False}}) + with moderation_app.app_context(): + assert factory.moderation_for_inputs({}) == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + moderation_app.extensions[API_MODERATION_EXTENSION_KEY] = object() + assert factory.moderation_for_inputs({}) == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert requests.calls == [] + + +def test_api_factory_requires_root_bundle(moderation_app: Flask) -> None: + moderation_app.extensions[API_MODERATION_EXTENSION_KEY] = object() + with moderation_app.app_context(), pytest.raises(TypeError, match="API moderation callbacks are not configured"): + ModerationFactory("api", "app", _TENANT_ID, {}).moderation_for_inputs({}) + + +def test_api_factory_validation_uses_injected_real_repository(moderation_app: Flask, requests: _Requests) -> None: + with moderation_app.app_context(): + ModerationFactory.validate_config( + "api", + _TENANT_ID, + {"inputs_config": {"enabled": True}, "outputs_config": {}, "api_based_extension_id": _EXTENSION_ID}, + ) + with pytest.raises(ValueError, match="API-based Extension not found"): + ModerationFactory.validate_config( + "api", + "foreign", + {"inputs_config": {"enabled": True}, "outputs_config": {}, "api_based_extension_id": _EXTENSION_ID}, + ) + assert requests.calls == [] + + +@pytest.fixture +def scanned_providers() -> Iterator[None]: + code_based_extension.init() + yield + code_based_extension.init() + + +@pytest.mark.usefixtures("scanned_providers") +@pytest.mark.parametrize("name", ["keywords", "openai_moderation"]) +def test_scanned_provider_constructor_and_class_validation_are_unchanged(name: str) -> None: + valid = { + "inputs_config": {"enabled": True, "preset_response": "Blocked"}, + "outputs_config": {"enabled": False}, + "keywords": "blocked", + } + ModerationFactory.validate_config(name, _TENANT_ID, valid) + factory = ModerationFactory( + name, "app", _TENANT_ID, {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}} + ) + assert factory.moderation_for_inputs({}) == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert factory.moderation_for_outputs("text") == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + + +@pytest.mark.usefixtures("scanned_providers") +class TestModerationFactoryIntegration: + """Exercise factory dispatch through real scanned moderation providers.""" + + def test_factory_delegates_to_extension(self) -> None: + """Pass settings and payloads to the scanned keywords provider.""" + factory = ModerationFactory( + "keywords", + "app", + _TENANT_ID, + {"inputs_config": {"enabled": True, "preset_response": "Blocked"}, "keywords": "bad"}, + ) + result = factory.moderation_for_inputs({"field": "value"}, "query") + assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked") + assert result.flagged is False + assert factory.moderation_for_inputs({"text": "BAD"}) == ModerationInputsResult( + flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked" + ) + + def test_factory_validate_config_delegates(self) -> None: + """Run the actual provider's form rules through factory class validation.""" + valid: dict[str, object] = { + "inputs_config": {"enabled": True, "preset_response": "Blocked"}, + "outputs_config": {"enabled": False}, + "keywords": "bad", + } + ModerationFactory.validate_config("keywords", _TENANT_ID, valid) + invalid = dict(valid) + del invalid["keywords"] + with pytest.raises(ValueError, match="^keywords is required$"): + ModerationFactory.validate_config("keywords", _TENANT_ID, invalid) diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py index 4d4210ada059e1..32362136811ae7 100644 --- a/api/tests/unit_tests/extensions/test_ext_application_services.py +++ b/api/tests/unit_tests/extensions/test_ext_application_services.py @@ -2,6 +2,7 @@ import json import logging +import sys from collections.abc import Mapping from decimal import Decimal from io import BytesIO @@ -20,6 +21,8 @@ from core.credit_usage import CreditUsageAppType, CreditUsageCreatedBy from core.llm_generator.prompts import CONVERSATION_TITLE_PROMPT from core.model_context import get_credit_usage_metadata, use_credit_usage_metadata +from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult +from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory from core.plugin.impl import base as plugin_http from core.tools.tool_file_manager import ToolFileManager from enums import DeploymentEdition, WebAppAccessMode @@ -196,6 +199,44 @@ def _redis() -> RedisClientWrapper: return client +@pytest.mark.skipif(sys.platform == "win32", reason="Existing tracing composition requires POSIX os.register_at_fork") +def test_init_app_binds_api_moderation_to_real_factory(sqlite_session_factory: sessionmaker[Session]) -> None: + """The actual root registers the callbacks consumed by input/output/form dispatch.""" + from models.api_based_extension import APIBasedExtension + + tenant_id = str(uuid4()) + extension_id = str(uuid4()) + extension = APIBasedExtension( + tenant_id=tenant_id, + name="Moderation", + api_endpoint="https://moderation.example.test", + api_key="ciphertext", + ) + extension.id = extension_id + with sqlite_session_factory.begin() as session: + session.add(extension) + app = Flask(__name__) + ext_application_services.init_app(app) + callbacks = app.extensions[API_MODERATION_EXTENSION_KEY] + assert isinstance(callbacks, APIModerationCallbacks) + with app.app_context(): + assert ( + callbacks.validate_config == ext_application_services.application_services().api_moderation.validate_config + ) + ModerationFactory.validate_config( + "api", + tenant_id, + {"inputs_config": {"enabled": True}, "outputs_config": {}, "api_based_extension_id": extension_id}, + ) + disabled = ModerationFactory( + "api", "app", tenant_id, {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}} + ) + assert disabled.moderation_for_inputs({}) == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert disabled.moderation_for_outputs("text") == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + with pytest.raises(ValueError, match=r"^The config is not set\.$"): + ModerationFactory("api", "app", tenant_id, None).moderation_for_inputs({}) + + @pytest.mark.parametrize( ("deployment_edition", "initialization_password", "session_validated", "setup_exists", "expected"), [ diff --git a/api/tests/unit_tests/services/test_api_based_extension_adapters.py b/api/tests/unit_tests/services/test_api_based_extension_adapters.py index 3c2a2c3499bd48..6f2619b9b79262 100644 --- a/api/tests/unit_tests/services/test_api_based_extension_adapters.py +++ b/api/tests/unit_tests/services/test_api_based_extension_adapters.py @@ -4,8 +4,9 @@ import services.api_based_extension_adapters as module from models.api_based_extension import APIBasedExtensionPoint -from services.api_based_extension_adapters import APIBasedExtensionPingProbe, WorkspaceTokenCipher +from services.api_based_extension_adapters import APIBasedExtensionPingProbe, APIModerationGateway, WorkspaceTokenCipher from services.api_based_extension_application_service import APIBasedExtensionConnectionError +from services.api_moderation_service import ModerationInputParams, ModerationOutputParams def test_workspace_token_cipher_delegates_to_the_platform_encrypter(monkeypatch: pytest.MonkeyPatch) -> None: @@ -58,3 +59,43 @@ def test_ping_probe_wraps_transport_failures(monkeypatch: pytest.MonkeyPatch) -> with pytest.raises(APIBasedExtensionConnectionError, match="connection error: request timeout"): APIBasedExtensionPingProbe().ping("https://ext.example.com", "secret") + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_moderation_gateway_translates_point_and_validated_parameters(direction: str) -> None: + response = object() + calls: list[tuple[str, str, APIBasedExtensionPoint, dict[str, object]]] = [] + + def request(endpoint: str, key: str, point: APIBasedExtensionPoint, params: dict[str, object]) -> object: + calls.append((endpoint, key, point, params)) + return response + + gateway = APIModerationGateway(request=request) + if direction == "inputs": + params = ModerationInputParams(app_id="app", inputs={"field": [1, True]}, query="hello") + assert gateway.inputs("https://extension.example.test", "plaintext-key", params) is response + point = APIBasedExtensionPoint.APP_MODERATION_INPUT + expected = {"app_id": "app", "inputs": {"field": [1, True]}, "query": "hello"} + else: + output_params = ModerationOutputParams(app_id="app", text="hello") + assert gateway.outputs("https://extension.example.test", "plaintext-key", output_params) is response + point = APIBasedExtensionPoint.APP_MODERATION_OUTPUT + expected = {"app_id": "app", "text": "hello"} + assert calls == [("https://extension.example.test", "plaintext-key", point, expected)] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_moderation_gateway_preserves_request_failure_identity(direction: str) -> None: + failure = ValueError("request timeout") + + def request(_endpoint: str, _key: str, _point: APIBasedExtensionPoint, _params: dict[str, object]) -> object: + raise failure + + gateway = APIModerationGateway(request=request) + if direction == "inputs": + with pytest.raises(ValueError, match="request timeout") as raised: + gateway.inputs("https://extension.example.test", "plaintext-key", ModerationInputParams()) + else: + with pytest.raises(ValueError, match="request timeout") as raised: + gateway.outputs("https://extension.example.test", "plaintext-key", ModerationOutputParams(text="hello")) + assert raised.value is failure diff --git a/api/tests/unit_tests/services/test_api_moderation_service.py b/api/tests/unit_tests/services/test_api_moderation_service.py new file mode 100644 index 00000000000000..50e3a5264951d9 --- /dev/null +++ b/api/tests/unit_tests/services/test_api_moderation_service.py @@ -0,0 +1,359 @@ +import re +from collections.abc import Iterator, Mapping + +import pytest +from pydantic import ValidationError +from sqlalchemy import Engine, create_engine, event +from sqlalchemy.orm import Session, sessionmaker + +from models.api_based_extension import APIBasedExtension +from models.base import TypeBase +from repositories.api_based_extension_repository import APIBasedExtensionRepository +from services.api_moderation_service import ( + APIModerationConfig, + APIModerationService, + DisabledDirection, + ModerationInputParams, + ModerationOutputParams, + parse_direction, +) + +_EXTENSION_ID = "a0000000-0000-0000-0000-000000000001" +_FOREIGN_EXTENSION_ID = "a0000000-0000-0000-0000-000000000002" +_MISSING_EXTENSION_ID = "a0000000-0000-0000-0000-000000000003" +_TENANT_ID = "a0000000-0000-0000-0000-000000000004" +_FOREIGN_TENANT_ID = "a0000000-0000-0000-0000-000000000005" +_ENDPOINT = "https://moderation.example.test/check" +_EXTENSION_NOT_FOUND = r"^API-based Extension not found\. Please check it again\.$" + + +class _Outbound: + """Explicit capabilities that observe ordering after a real repository read.""" + + def __init__(self, events: list[str]) -> None: + self.events = events + self.response: object = {"flagged": False, "action": "direct_output", "preset_response": ""} + self.failure: tuple[str, RuntimeError] | None = None + self.params: ModerationInputParams | ModerationOutputParams | None = None + + def decrypt(self, tenant_id: str, ciphertext: str) -> str: + assert self.events == ["checkout", "checkin"] + assert (tenant_id, ciphertext) == (_TENANT_ID, "encrypted-key") + self.events.append("decrypt") + if self.failure is not None and self.failure[0] == "decrypt": + raise self.failure[1] + return "decrypted-key" + + def inputs(self, endpoint: str, key: str, params: ModerationInputParams) -> object: + return self._request(endpoint, key, params) + + def outputs(self, endpoint: str, key: str, params: ModerationOutputParams) -> object: + return self._request(endpoint, key, params) + + def _request(self, endpoint: str, key: str, params: ModerationInputParams | ModerationOutputParams) -> object: + assert self.events == ["checkout", "checkin", "decrypt"] + assert (endpoint, key) == (_ENDPOINT, "decrypted-key") + self.events.append("request") + self.params = params + if self.failure is not None and self.failure[0] == "request": + raise self.failure[1] + return self.response + + +@pytest.fixture +def api_config() -> APIModerationConfig: + return { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": True}, + "api_based_extension_id": _EXTENSION_ID, + } + + +@pytest.fixture +def lookup_events(sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session]) -> Iterator[list[str]]: + """Commit owned/foreign rows, then observe real read connection ownership.""" + target = APIBasedExtension( + tenant_id=_TENANT_ID, name="Target extension", api_endpoint=_ENDPOINT, api_key="encrypted-key" + ) + target.id = _EXTENSION_ID + foreign = APIBasedExtension( + tenant_id=_FOREIGN_TENANT_ID, + name="Foreign extension", + api_endpoint="https://moderation.example.test/foreign", + api_key="foreign-key", + ) + foreign.id = _FOREIGN_EXTENSION_ID + with sqlite_session_factory.begin() as session: + session.add_all((target, foreign)) + events: list[str] = [] + + def checkout(*_args: object) -> None: + events.append("checkout") + + def checkin(*_args: object) -> None: + events.append("checkin") + + event.listen(sqlite_engine, "checkout", checkout) + event.listen(sqlite_engine, "checkin", checkin) + try: + yield events + finally: + event.remove(sqlite_engine, "checkout", checkout) + event.remove(sqlite_engine, "checkin", checkin) + + +@pytest.fixture +def outbound(lookup_events: list[str]) -> _Outbound: + return _Outbound(lookup_events) + + +@pytest.fixture +def service(sqlite_session_factory: sessionmaker[Session], outbound: _Outbound) -> APIModerationService: + return APIModerationService( + find_extension=APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension, + decrypt_key=outbound.decrypt, + request_inputs=outbound.inputs, + request_outputs=outbound.outputs, + ) + + +def _moderate(service: APIModerationService, raw: Mapping[str, object] | None, direction: str) -> object: + if direction == "inputs": + return service.moderate_inputs(_TENANT_ID, "test-app-id", raw, {"q": "a"}, "hello") + return service.moderate_outputs(_TENANT_ID, "test-app-id", raw, "hello world") + + +def test_moderation_input_params() -> None: + params = ModerationInputParams(app_id="app-1", inputs={"key": "val"}, query="test query") + assert params.app_id == "app-1" + assert params.inputs == {"key": "val"} + assert params.query == "test query" + params_default = ModerationInputParams() + assert params_default.app_id == "" + assert params_default.inputs == {} + assert params_default.query == "" + + +def test_moderation_output_params() -> None: + params = ModerationOutputParams(app_id="app-1", text="test text") + assert params.app_id == "app-1" + assert params.text == "test text" + with pytest.raises(ValidationError): + ModerationOutputParams.model_validate({}) + + +def test_validate_config_success( + service: APIModerationService, api_config: APIModerationConfig, lookup_events: list[str] +) -> None: + service.validate_config(_TENANT_ID, api_config) + assert lookup_events == ["checkout", "checkin"] + + +@pytest.mark.parametrize( + ("config", "message"), + [ + ({}, "inputs_config must be a dict"), + ({"inputs_config": [], "outputs_config": []}, "inputs_config must be a dict"), + ({"inputs_config": {}}, "outputs_config must be a dict"), + ( + {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, + "At least one of inputs_config or outputs_config must be enabled", + ), + ( + {"inputs_config": {"enabled": True}, "outputs_config": {"enabled": True}}, + "api_based_extension_id is required", + ), + ], +) +def test_validate_config_rejects_invalid_config_before_lookup( + service: APIModerationService, config: dict[str, object], message: str, lookup_events: list[str] +) -> None: + with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): + service.validate_config(_TENANT_ID, config) + assert lookup_events == [] + + +@pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) +def test_validate_config_extension_not_found( + service: APIModerationService, extension_id: str, api_config: APIModerationConfig, lookup_events: list[str] +) -> None: + api_config["api_based_extension_id"] = extension_id + with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): + service.validate_config(_TENANT_ID, api_config) + assert lookup_events == ["checkout", "checkin"] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_enabled_moderation_releases_connection_before_external_io( + service: APIModerationService, + direction: str, + api_config: APIModerationConfig, + lookup_events: list[str], + outbound: _Outbound, +) -> None: + if direction == "inputs": + outbound.response = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} + expected = {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"} + else: + expected = {"app_id": "test-app-id", "text": "hello world"} + assert _moderate(service, api_config, direction) is outbound.response + assert outbound.params is not None + assert outbound.params.model_dump() == expected + assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID, None]) +def test_enabled_moderation_extension_not_found( + service: APIModerationService, + direction: str, + extension_id: str | None, + api_config: APIModerationConfig, + lookup_events: list[str], +) -> None: + if extension_id is None: + del api_config["api_based_extension_id"] + else: + api_config["api_based_extension_id"] = extension_id + with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): + _moderate(service, api_config, direction) + assert lookup_events == ["checkout", "checkin"] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_disabled_moderation_skips_lookup( + service: APIModerationService, direction: str, api_config: APIModerationConfig, lookup_events: list[str] +) -> None: + if direction == "inputs": + api_config["inputs_config"] = {"enabled": False} + else: + api_config["outputs_config"] = {"enabled": False} + assert _moderate(service, api_config, direction) == { + "flagged": False, + "action": "direct_output", + "preset_response": "", + } + assert lookup_events == [] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +def test_moderation_without_config_skips_lookup( + service: APIModerationService, direction: str, lookup_events: list[str] +) -> None: + with pytest.raises(ValueError, match=r"^The config is not set\.$"): + _moderate(service, None, direction) + assert lookup_events == [] + + +def test_parse_direction_no_config(lookup_events: list[str]) -> None: + with pytest.raises(ValueError, match=r"^The config is not set\.$"): + parse_direction(None, "inputs_config") + assert lookup_events == [] + + +def test_lookup_failure_releases_connection( + service: APIModerationService, api_config: APIModerationConfig, lookup_events: list[str], sqlite_engine: Engine +) -> None: + failure = RuntimeError("lookup failed") + + def fail_query(*_args: object) -> None: + raise failure + + event.listen(sqlite_engine, "before_cursor_execute", fail_query) + try: + with pytest.raises(RuntimeError) as exc_info: + service.moderate_outputs(_TENANT_ID, "test-app-id", api_config, "test") + finally: + event.remove(sqlite_engine, "before_cursor_execute", fail_query) + assert exc_info.value is failure + assert lookup_events == ["checkout", "checkin"] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("stage", ["decrypt", "request"]) +def test_external_failure_preserves_identity_after_checkin( + service: APIModerationService, + api_config: APIModerationConfig, + outbound: _Outbound, + lookup_events: list[str], + direction: str, + stage: str, +) -> None: + failure = RuntimeError(f"{stage} failed") + outbound.failure = (stage, failure) + with pytest.raises(RuntimeError) as exc_info: + _moderate(service, api_config, direction) + assert exc_info.value is failure + expected = ["checkout", "checkin", "decrypt"] + if stage == "request": + expected.append("request") + assert lookup_events == expected + + +@pytest.mark.parametrize("value", ["yes", 1, [False]]) +def test_non_boolean_truthiness_is_preserved( + service: APIModerationService, api_config: APIModerationConfig, value: object, lookup_events: list[str] +) -> None: + api_config["inputs_config"] = {"enabled": value} + service.moderate_inputs(_TENANT_ID, "app", api_config, {}) + assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + + +@pytest.mark.parametrize("selected", [None, [], "invalid", 1, {}]) +def test_selected_malformed_direction_retains_native_error( + service: APIModerationService, selected: object, lookup_events: list[str] +) -> None: + raw = {"inputs_config": selected} + with pytest.raises((KeyError, TypeError)): + service.moderate_inputs(_TENANT_ID, "app", raw, {}) + assert lookup_events == [] + + +def test_disabled_directions_ignore_opposite_malformed_values( + service: APIModerationService, lookup_events: list[str] +) -> None: + assert parse_direction({"inputs_config": {"enabled": False}, "outputs_config": None}, "inputs_config") == ( + DisabledDirection() + ) + for direction in ("inputs", "outputs"): + assert _moderate( + service, {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, direction + ) == {"flagged": False, "action": "direct_output", "preset_response": ""} + assert lookup_events == [] + + +def test_service_uses_explicit_database_instead_of_global( + sqlite_session_factory: sessionmaker[Session], api_config: APIModerationConfig +) -> None: + """The autouse global DB is empty; only the independently supplied DB owns this ID.""" + assert ( + APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension(_TENANT_ID, _EXTENSION_ID) + is None + ) + engine = create_engine("sqlite://") + try: + TypeBase.metadata.create_all(engine) + explicit_factory = sessionmaker(bind=engine) + repository = APIBasedExtensionRepository(session_factory=explicit_factory) + target = APIBasedExtension( + tenant_id=_TENANT_ID, name="Explicit database", api_endpoint=_ENDPOINT, api_key="encrypted-key" + ) + target.id = _EXTENSION_ID + with explicit_factory.begin() as session: + session.add(target) + outbound = _Outbound([]) + explicit_service = APIModerationService( + find_extension=repository.find_extension, + decrypt_key=outbound.decrypt, + request_inputs=outbound.inputs, + request_outputs=outbound.outputs, + ) + explicit_service.validate_config(_TENANT_ID, api_config) + assert ( + APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension( + _TENANT_ID, _EXTENSION_ID + ) + is None + ) + finally: + engine.dispose() diff --git a/api/tests/unit_tests/services/test_code_based_extension_service.py b/api/tests/unit_tests/services/test_code_based_extension_service.py index cd849bd8d5215c..f6fcdb5b4d8df9 100644 --- a/api/tests/unit_tests/services/test_code_based_extension_service.py +++ b/api/tests/unit_tests/services/test_code_based_extension_service.py @@ -3,9 +3,15 @@ import pytest +from extensions.ext_code_based_extension import code_based_extension from services.code_based_extension_service import CodeBasedExtensionService +def test_real_scanned_moderation_discovery_keeps_builtins_private() -> None: + code_based_extension.init() + assert CodeBasedExtensionService.get_code_based_extension("moderation") == [] + + class TestCodeBasedExtensionService: def test_should_return_only_non_builtin_extensions_with_public_fields( self, monkeypatch: pytest.MonkeyPatch From 0fe83ce912fcc0272a6460cbc352e9261d9979a5 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 11:02:22 +0800 Subject: [PATCH 05/12] refactor(api): qualify moderation factory wiring --- api/extensions/ext_application_services.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py index 472a73cb4dde73..c82ded0629214a 100644 --- a/api/extensions/ext_application_services.py +++ b/api/extensions/ext_application_services.py @@ -14,10 +14,10 @@ from pydantic import ValidationError from sqlalchemy.orm import Session, sessionmaker +import core.moderation.factory as moderation_factory from configs import dify_config from constants.dsl_version import CURRENT_APP_DSL_VERSION from core.db.session_factory import get_session_maker -from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks from core.schemas.schema_manager import SchemaManager from core.tools.tool_file_manager import ToolFileManager from core.tools.tool_manager import ToolManager @@ -907,7 +907,7 @@ def init_app(app: Flask) -> None: redis=redis_client, ) app.extensions[_EXTENSION_KEY] = services - app.extensions[API_MODERATION_EXTENSION_KEY] = APIModerationCallbacks( + app.extensions[moderation_factory.API_MODERATION_EXTENSION_KEY] = moderation_factory.APIModerationCallbacks( validate_config=services.api_moderation.validate_config, moderate_inputs=services.api_moderation.moderate_inputs, moderate_outputs=services.api_moderation.moderate_outputs, From c4c07ad114e22f8e18d0569e0f7beb703978a4b4 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 11:32:50 +0800 Subject: [PATCH 06/12] test(api): supply moderation dependency in workflow wiring fixture --- .../knowledge_fs/test_workflow_runtime.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/api/tests/unit_tests/services/knowledge_fs/test_workflow_runtime.py b/api/tests/unit_tests/services/knowledge_fs/test_workflow_runtime.py index 381733d6ddd521..2f0200a3536b71 100644 --- a/api/tests/unit_tests/services/knowledge_fs/test_workflow_runtime.py +++ b/api/tests/unit_tests/services/knowledge_fs/test_workflow_runtime.py @@ -3,7 +3,7 @@ import time from collections.abc import Callable from dataclasses import dataclass, field -from typing import cast +from typing import Never, cast import pytest from flask import Flask @@ -18,6 +18,7 @@ from graphon.runtime import RuntimeState, VariablePool from graphon.variables import StringSegment from models.knowledge_fs import KnowledgeFSAppSpaceJoinType +from services.api_moderation_service import APIModerationService from services.knowledge_fs import runtime as runtime_module from services.knowledge_fs import workflow_runtime from services.knowledge_fs.knowledge_retrieval_v2.knowledge_retrieval_v2_node import KnowledgeRetrievalV2Node @@ -78,6 +79,7 @@ class _FakeAccounts: @dataclass class _FakeApplicationServices: tracing: TracingServices + api_moderation: APIModerationService accounts: _FakeAccounts = field(default_factory=_FakeAccounts) @@ -90,10 +92,20 @@ def test_application_registers_lazy_workflow_runtime_dependencies(monkeypatch: p monkeypatch.setattr(workflow_runtime.session_factory, "get_session_maker", lambda: session_maker) monkeypatch.setattr(ext_application_services, "get_session_maker", lambda: session_maker) tracing = build_tracing_services(database_client=session_maker) + + def unexpected_moderation(*_args: object) -> Never: + raise AssertionError("workflow runtime registration must not run API moderation") + + api_moderation = APIModerationService( + find_extension=unexpected_moderation, + decrypt_key=unexpected_moderation, + request_inputs=unexpected_moderation, + request_outputs=unexpected_moderation, + ) monkeypatch.setattr( ext_application_services, "build_application_services", - lambda **_kwargs: _FakeApplicationServices(tracing=tracing), + lambda **_kwargs: _FakeApplicationServices(tracing=tracing, api_moderation=api_moderation), ) ext_application_services.init_app(app) From 4eb880fa3457fdd88a5398bfa6746d993afefeb6 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 15:05:30 +0800 Subject: [PATCH 07/12] fix(api): validate moderation configuration and input types --- .../api_based_extension_repository.py | 13 +- api/services/api_moderation_service.py | 97 ++-- .../test_api_based_extension_requestor.py | 34 ++ .../core/moderation/test_factory.py | 59 ++- .../test_api_based_extension_adapters.py | 80 +++- .../services/test_api_moderation_service.py | 436 +++++++++++++++--- 6 files changed, 614 insertions(+), 105 deletions(-) diff --git a/api/repositories/api_based_extension_repository.py b/api/repositories/api_based_extension_repository.py index d350dec47a4488..41d23d46c77cf2 100644 --- a/api/repositories/api_based_extension_repository.py +++ b/api/repositories/api_based_extension_repository.py @@ -31,7 +31,12 @@ def list_extensions(self, workspace_id: str) -> tuple[APIBasedExtensionRecord, . ) @override - def find_extension(self, workspace_id: str, extension_id: object) -> APIBasedExtensionRecord | None: + def find_extension(self, workspace_id: str, extension_id: str) -> APIBasedExtensionRecord | None: + """Read string owner/extension IDs and return a detached record or None. + + Perform no writes; close the read session on success and query failure. + Query exceptions propagate unchanged. + """ with self._session_factory() as session: extension = self._find(session, workspace_id, extension_id) return self._to_record(extension) if extension is not None else None @@ -79,7 +84,11 @@ def delete_extension(self, workspace_id: str, extension_id: str) -> None: session.delete(self._require(session, workspace_id, extension_id)) @staticmethod - def _find(session: Session, workspace_id: str, extension_id: object) -> APIBasedExtension | None: + def _find(session: Session, workspace_id: str, extension_id: str) -> APIBasedExtension | None: + """Query an owned ORM row or None using the caller's active session. + + The caller owns commit and cleanup; query exceptions propagate unchanged. + """ return session.scalar( select(APIBasedExtension) .where(APIBasedExtension.tenant_id == workspace_id, APIBasedExtension.id == extension_id) diff --git a/api/services/api_moderation_service.py b/api/services/api_moderation_service.py index 34c4910594b7d1..f6bbe957ba5ad7 100644 --- a/api/services/api_moderation_service.py +++ b/api/services/api_moderation_service.py @@ -1,36 +1,42 @@ """API moderation with explicit, workspace-scoped persistence and outbound capabilities. -Form settings and runtime direction selection have distinct legacy contracts. Parse -only the selected runtime direction, and finish request validation before any I/O. +Complete form settings require both directions and a string extension ID. Runtime +selection validates only its direction, and enabled requests are validated before I/O. """ -import operator from collections.abc import Callable, Mapping from dataclasses import dataclass -from typing import Literal, TypedDict +from typing import Annotated, Literal, TypedDict -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, InstanceOf, JsonValue, TypeAdapter +from graphon.file import File from services.api_based_extension_application_service import APIBasedExtensionRecord -class APIModerationDirectionConfig(TypedDict, total=False): - """Legacy enabled values use Python truthiness without boolean coercion.""" +class APIModerationDirectionConfig(TypedDict): + """A configured direction explicitly chooses a boolean enable state.""" - enabled: object + enabled: bool -class APIModerationConfig(TypedDict, total=False): - """Stored API settings; an absent runtime ID still reaches the scoped lookup.""" +class APIModerationConfig(TypedDict): + """Complete authored settings; partial runtime values enter through raw mappings.""" inputs_config: APIModerationDirectionConfig outputs_config: APIModerationDirectionConfig - api_based_extension_id: object + api_based_extension_id: str + + +_direction_adapter = TypeAdapter(APIModerationDirectionConfig) +_extension_id_adapter = TypeAdapter(Annotated[str, Field(strict=True, min_length=1)]) class ModerationInputParams(BaseModel): + """Keep JSON mappings as JSON and admit file variants only as existing File instances.""" + app_id: str = "" - inputs: dict[str, object] = Field(default_factory=dict) + inputs: dict[str, JsonValue | InstanceOf[File] | list[InstanceOf[File]]] = Field(default_factory=dict) query: str = "" @@ -46,9 +52,9 @@ class DisabledDirection: @dataclass(frozen=True, slots=True) class EnabledDirection: - """The original lookup key, preserved without string conversion.""" + """The selected enabled direction has a validated, nonempty string lookup key.""" - extension_id: object + extension_id: str def parse_direction( @@ -56,31 +62,28 @@ def parse_direction( ) -> DisabledDirection | EnabledDirection: """Parse one runtime direction without inspecting the opposite direction. - Missing config raises the existing ValueError. Native indexing errors and - truthiness are retained for malformed selected values. This function does no I/O. + Missing config raises ValueError; malformed selected settings raise + ValidationError. Disabled settings return before ID validation. No I/O occurs. """ if raw is None: raise ValueError("The config is not set.") - enabled: object = operator.itemgetter("enabled")(operator.itemgetter(direction)(raw)) - if enabled: - return EnabledDirection(raw.get("api_based_extension_id", "")) - return DisabledDirection() + selected = _direction_adapter.validate_python(raw.get(direction), strict=True) + if not selected["enabled"]: + return DisabledDirection() + return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) def _parse_form(raw: Mapping[str, object]) -> EnabledDirection: - """Parse form settings in their existing error order without any I/O.""" - inputs_config = raw.get("inputs_config") - if not isinstance(inputs_config, dict): - raise ValueError("inputs_config must be a dict") - outputs_config = raw.get("outputs_config") - if not isinstance(outputs_config, dict): - raise ValueError("outputs_config must be a dict") - if not inputs_config.get("enabled") and not outputs_config.get("enabled"): + """Validate both directions, require one enabled, then parse the ID without I/O. + + Malformed settings raise ValidationError. Two disabled directions retain their + business error before ID validation, including when the ID is absent or invalid. + """ + inputs_config = _direction_adapter.validate_python(raw.get("inputs_config"), strict=True) + outputs_config = _direction_adapter.validate_python(raw.get("outputs_config"), strict=True) + if not inputs_config["enabled"] and not outputs_config["enabled"]: raise ValueError("At least one of inputs_config or outputs_config must be enabled") - extension_id = raw.get("api_based_extension_id") - if not extension_id: - raise ValueError("api_based_extension_id is required") - return EnabledDirection(extension_id) + return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) class APIModerationService: @@ -93,11 +96,12 @@ class APIModerationService: def __init__( self, *, - find_extension: Callable[[str, object], APIBasedExtensionRecord | None], + find_extension: Callable[[str, str], APIBasedExtensionRecord | None], decrypt_key: Callable[[str, str], str], request_inputs: Callable[[str, str, ModerationInputParams], object], request_outputs: Callable[[str, str, ModerationOutputParams], object], ) -> None: + """Store all four required capabilities without performing I/O.""" self._find_extension = find_extension self._decrypt_key = decrypt_key self._request_inputs = request_inputs @@ -106,8 +110,9 @@ def __init__( def validate_config(self, tenant_id: str, raw: Mapping[str, object]) -> None: """Require valid form settings and an owned extension without outbound I/O. - Invalid settings or absence raise the existing ValueError; lookup failures - propagate after its session closes. Successful validation changes no state. + Malformed settings raise ValidationError; both-disabled settings or an + absent owned row raise ValueError. Lookup failures propagate after session + cleanup. Successful validation changes no state. """ self._require_extension(tenant_id, _parse_form(raw).extension_id) @@ -116,18 +121,19 @@ def moderate_inputs( tenant_id: str, app_id: str, raw: Mapping[str, object] | None, - inputs: dict[str, object], + inputs: Mapping[str, object], query: str = "", ) -> object: """Return the disabled result or raw input response for facade validation. - Parse the selected direction and validate request parameters before lookup. - Lookup, decrypt and request failures propagate unchanged in that order. + Raw mappings admit dynamic variable names with JSON, File or list[File] + values. Enabled settings and payloads must validate before lookup. Disabled + settings skip payload validation and all I/O. Dependency failures propagate. """ selection = parse_direction(raw, "inputs_config") if isinstance(selection, DisabledDirection): return {"flagged": False, "action": "direct_output", "preset_response": ""} - params = ModerationInputParams(app_id=app_id, inputs=inputs, query=query) + params = ModerationInputParams.model_validate({"app_id": app_id, "inputs": inputs, "query": query}) extension = self._require_extension(tenant_id, selection.extension_id) key = self._decrypt_key(tenant_id, extension.api_key) return self._request_inputs(extension.api_endpoint, key, params) @@ -135,8 +141,9 @@ def moderate_inputs( def moderate_outputs(self, tenant_id: str, app_id: str, raw: Mapping[str, object] | None, text: str) -> object: """Return the disabled result or raw output response for facade validation. - Parse the selected direction and validate request parameters before lookup. - Lookup, decrypt and request failures propagate unchanged in that order. + Enabled settings and request parameters validate before lookup. Disabled + settings skip payload validation and all I/O. Lookup, decrypt and request + failures propagate unchanged in that order. """ selection = parse_direction(raw, "outputs_config") if isinstance(selection, DisabledDirection): @@ -146,8 +153,12 @@ def moderate_outputs(self, tenant_id: str, app_id: str, raw: Mapping[str, object key = self._decrypt_key(tenant_id, extension.api_key) return self._request_outputs(extension.api_endpoint, key, params) - def _require_extension(self, tenant_id: str, extension_id: object) -> APIBasedExtensionRecord: - """Return an owned detached record or fail after the lookup session closes.""" + def _require_extension(self, tenant_id: str, extension_id: str) -> APIBasedExtensionRecord: + """Look up string tenant/extension IDs without outbound work. + + Return the owned detached record after session cleanup. Missing records + raise ValueError; lookup failures propagate unchanged after cleanup. + """ extension = self._find_extension(tenant_id, extension_id) if extension is None: raise ValueError("API-based Extension not found. Please check it again.") diff --git a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py index 1b002566071d63..b7d4b01b0c6b7e 100644 --- a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py +++ b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py @@ -6,6 +6,7 @@ from core.extension.api_based_extension_requestor import APIBasedExtensionRequestor from models.api_based_extension import APIBasedExtensionPoint +from services.api_based_extension_adapters import request_api_based_extension @pytest.fixture @@ -46,6 +47,39 @@ def test_request_success(install_client): assert request.headers["Authorization"] == "Bearer test_key" +@pytest.mark.parametrize( + ("point", "params"), + [ + ( + APIBasedExtensionPoint.APP_MODERATION_INPUT, + {"app_id": "app", "inputs": {"field": [1, True, None]}, "query": "hello"}, + ), + (APIBasedExtensionPoint.APP_MODERATION_OUTPUT, {"app_id": "app", "text": "hello"}), + ], +) +def test_request_adapter_preserves_moderation_wire_contract( + install_client, point: APIBasedExtensionPoint, params: dict[str, object] +) -> None: + """Use the fixture's in-process transport for each moderation point and payload. + + Require one authenticated POST with unchanged JSON and its decoded response. + """ + requests, _ = install_client( + lambda _: httpx.Response(200, json={"flagged": True, "action": "direct_output", "preset_response": "Blocked"}) + ) + + result = request_api_based_extension("https://moderation.example.test/check", "plaintext-key", point, params) + + assert result == {"flagged": True, "action": "direct_output", "preset_response": "Blocked"} + assert len(requests) == 1 + request = requests[0] + assert request.method == "POST" + assert str(request.url) == "https://moderation.example.test/check" + assert json.loads(request.content) == {"point": point.value, "params": params} + assert request.headers["Content-Type"] == "application/json" + assert request.headers["Authorization"] == "Bearer plaintext-key" + + def test_request_with_ssrf_proxy( install_client, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] ): diff --git a/api/tests/unit_tests/core/moderation/test_factory.py b/api/tests/unit_tests/core/moderation/test_factory.py index 7af282adaa619c..e59b9ccd4d5e90 100644 --- a/api/tests/unit_tests/core/moderation/test_factory.py +++ b/api/tests/unit_tests/core/moderation/test_factory.py @@ -6,6 +6,7 @@ from sqlalchemy import Engine, event from sqlalchemy.orm import Session, sessionmaker +from core.extension.extensible import ExtensionModule from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory from extensions.ext_code_based_extension import code_based_extension @@ -127,6 +128,30 @@ def test_api_factory_binds_once_at_first_operation(moderation_app: Flask, reques assert requests.calls == [] +def test_api_factory_outputs_reuse_callbacks_after_app_context_closes( + moderation_app: Flask, requests: _Requests +) -> None: + """Use the owned-row app fixture to bind and call the real service twice. + + Both outputs and recorded requests must survive closing the first app context. + """ + factory = ModerationFactory( + "api", "app", _TENANT_ID, {"outputs_config": {"enabled": True}, "api_based_extension_id": _EXTENSION_ID} + ) + expected = ModerationOutputsResult( + flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked by API" + ) + with moderation_app.app_context(): + assert factory.moderation_for_outputs("first") == expected + assert factory.moderation_for_outputs("second") == expected + assert requests.calls == [ + (_TENANT_ID, "encrypted-key"), + ("https://moderation.example.test/check", "plaintext", ModerationOutputParams(app_id="app", text="first")), + (_TENANT_ID, "encrypted-key"), + ("https://moderation.example.test/check", "plaintext", ModerationOutputParams(app_id="app", text="second")), + ] + + def test_api_factory_requires_root_bundle(moderation_app: Flask) -> None: moderation_app.extensions[API_MODERATION_EXTENSION_KEY] = object() with moderation_app.app_context(), pytest.raises(TypeError, match="API moderation callbacks are not configured"): @@ -134,17 +159,29 @@ def test_api_factory_requires_root_bundle(moderation_app: Flask) -> None: def test_api_factory_validation_uses_injected_real_repository(moderation_app: Flask, requests: _Requests) -> None: + """Validate owned settings through the fixture's repository without outbound calls. + + The same settings in another workspace must fail with the missing-row error. + """ with moderation_app.app_context(): ModerationFactory.validate_config( "api", _TENANT_ID, - {"inputs_config": {"enabled": True}, "outputs_config": {}, "api_based_extension_id": _EXTENSION_ID}, + { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": False}, + "api_based_extension_id": _EXTENSION_ID, + }, ) with pytest.raises(ValueError, match="API-based Extension not found"): ModerationFactory.validate_config( "api", "foreign", - {"inputs_config": {"enabled": True}, "outputs_config": {}, "api_based_extension_id": _EXTENSION_ID}, + { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": False}, + "api_based_extension_id": _EXTENSION_ID, + }, ) assert requests.calls == [] @@ -156,6 +193,24 @@ def scanned_providers() -> Iterator[None]: code_based_extension.init() +@pytest.mark.usefixtures("scanned_providers") +@pytest.mark.parametrize("operation", ["construct", "validate"]) +def test_factory_rejects_scanned_class_from_another_extension_module(operation: str) -> None: + """Misregister a scanned external-data class and require TypeError on either path. + + The scanned_providers fixture restores the registry after success or failure. + """ + provider = code_based_extension.module_extension(ExtensionModule.MODERATION, "keywords") + provider.extension_class = code_based_extension.extension_class(ExtensionModule.EXTERNAL_DATA_TOOL, "api") + + if operation == "construct": + with pytest.raises(TypeError, match="Extension keywords is not a moderation provider"): + ModerationFactory("keywords", "app", _TENANT_ID, {}) + else: + with pytest.raises(TypeError, match="Extension keywords is not a moderation provider"): + ModerationFactory.validate_config("keywords", _TENANT_ID, {}) + + @pytest.mark.usefixtures("scanned_providers") @pytest.mark.parametrize("name", ["keywords", "openai_moderation"]) def test_scanned_provider_constructor_and_class_validation_are_unchanged(name: str) -> None: diff --git a/api/tests/unit_tests/services/test_api_based_extension_adapters.py b/api/tests/unit_tests/services/test_api_based_extension_adapters.py index 6f2619b9b79262..97fff673188d61 100644 --- a/api/tests/unit_tests/services/test_api_based_extension_adapters.py +++ b/api/tests/unit_tests/services/test_api_based_extension_adapters.py @@ -1,12 +1,16 @@ +from typing import Literal from unittest.mock import MagicMock import pytest +from pydantic import JsonValue import services.api_based_extension_adapters as module +from graphon.file import File, FileTransferMethod, FileType from models.api_based_extension import APIBasedExtensionPoint from services.api_based_extension_adapters import APIBasedExtensionPingProbe, APIModerationGateway, WorkspaceTokenCipher from services.api_based_extension_application_service import APIBasedExtensionConnectionError from services.api_moderation_service import ModerationInputParams, ModerationOutputParams +from services.entities.message_entities import MessageInputValue def test_workspace_token_cipher_delegates_to_the_platform_encrypter(monkeypatch: pytest.MonkeyPatch) -> None: @@ -62,7 +66,8 @@ def test_ping_probe_wraps_transport_failures(monkeypatch: pytest.MonkeyPatch) -> @pytest.mark.parametrize("direction", ["inputs", "outputs"]) -def test_moderation_gateway_translates_point_and_validated_parameters(direction: str) -> None: +def test_moderation_gateway_translates_point_and_validated_parameters(direction: Literal["inputs", "outputs"]) -> None: + """Validated input/output parameters retain their point, payload and response identity.""" response = object() calls: list[tuple[str, str, APIBasedExtensionPoint, dict[str, object]]] = [] @@ -84,8 +89,79 @@ def request(endpoint: str, key: str, point: APIBasedExtensionPoint, params: dict assert calls == [("https://extension.example.test", "plaintext-key", point, expected)] +def test_input_domain_serialization_preserves_files_and_json() -> None: + """File instances serialize as files while ordinary file-shaped JSON stays intact.""" + attachment = File( + file_id="66666666-6666-4666-8666-666666666666", + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.com/input.pdf", + filename="input.pdf", + extension=".pdf", + mime_type="application/pdf", + size=12, + ) + file_shaped_json: dict[str, JsonValue] = { + "dify_model_identity": "__dify__file__", + "id": "77777777-7777-4777-8777-777777777777", + "type": "document", + "transfer_method": "remote_url", + "remote_url": "https://example.com/ordinary.json", + "filename": "ordinary.json", + "extension": ".json", + "mime_type": "application/json", + "size": 4, + "ordinary_json": {"keep": [1, True]}, + } + values: dict[str, MessageInputValue] = { + "动态变量": "value", + "nothing": None, + "empty_text": "", + "empty_object": {}, + "empty_list": [], + "nested": {"list": [{"checked": True}, None, ""]}, + "mixed": [1, True], + "file": attachment, + "files": [attachment], + "file_json": file_shaped_json, + } + params = ModerationInputParams(inputs=values) + calls: list[tuple[str, str, APIBasedExtensionPoint, dict[str, object]]] = [] + response = {"flagged": False} + + def request(endpoint: str, key: str, point: APIBasedExtensionPoint, payload: dict[str, object]) -> object: + calls.append((endpoint, key, point, payload)) + wire_inputs = payload["inputs"] + assert isinstance(wire_inputs, dict) + wire_mixed = wire_inputs["mixed"] + assert isinstance(wire_mixed, list) + assert type(wire_mixed[0]) is int + assert type(wire_mixed[1]) is bool + return response + + assert APIModerationGateway(request=request).inputs("https://extension.example.test", "plaintext-key", params) is ( + response + ) + assert params.inputs["file"] is attachment + files = params.inputs["files"] + assert isinstance(files, list) + assert len(files) == 1 + assert files[0] is attachment + assert isinstance(params.inputs["file_json"], dict) + assert params.inputs["file_json"] == file_shaped_json + expected = { + "app_id": "", + "inputs": {**values, "file": attachment.model_dump(), "files": [attachment.model_dump()]}, + "query": "", + } + assert calls == [ + ("https://extension.example.test", "plaintext-key", APIBasedExtensionPoint.APP_MODERATION_INPUT, expected) + ] + + @pytest.mark.parametrize("direction", ["inputs", "outputs"]) -def test_moderation_gateway_preserves_request_failure_identity(direction: str) -> None: +def test_moderation_gateway_preserves_request_failure_identity(direction: Literal["inputs", "outputs"]) -> None: + """Either gateway method propagates the original request failure instance.""" failure = ValueError("request timeout") def request(_endpoint: str, _key: str, _point: APIBasedExtensionPoint, _params: dict[str, object]) -> object: diff --git a/api/tests/unit_tests/services/test_api_moderation_service.py b/api/tests/unit_tests/services/test_api_moderation_service.py index 50e3a5264951d9..6ab0efe05df4c9 100644 --- a/api/tests/unit_tests/services/test_api_moderation_service.py +++ b/api/tests/unit_tests/services/test_api_moderation_service.py @@ -1,22 +1,27 @@ import re -from collections.abc import Iterator, Mapping +from collections.abc import Iterator +from typing import Literal import pytest -from pydantic import ValidationError +from pydantic import JsonValue, ValidationError from sqlalchemy import Engine, create_engine, event from sqlalchemy.orm import Session, sessionmaker -from models.api_based_extension import APIBasedExtension +from graphon.file import File, FileTransferMethod, FileType +from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint from models.base import TypeBase from repositories.api_based_extension_repository import APIBasedExtensionRepository +from services.api_based_extension_adapters import APIModerationGateway from services.api_moderation_service import ( APIModerationConfig, APIModerationService, DisabledDirection, + EnabledDirection, ModerationInputParams, ModerationOutputParams, parse_direction, ) +from services.entities.message_entities import MessageInputValue _EXTENSION_ID = "a0000000-0000-0000-0000-000000000001" _FOREIGN_EXTENSION_ID = "a0000000-0000-0000-0000-000000000002" @@ -25,6 +30,19 @@ _FOREIGN_TENANT_ID = "a0000000-0000-0000-0000-000000000005" _ENDPOINT = "https://moderation.example.test/check" _EXTENSION_NOT_FOUND = r"^API-based Extension not found\. Please check it again\.$" +_INVALID_EXTENSION_CONFIGS: tuple[dict[str, JsonValue], ...] = ( + {}, + {"api_based_extension_id": None}, + {"api_based_extension_id": ""}, + {"api_based_extension_id": False}, + {"api_based_extension_id": True}, + {"api_based_extension_id": 0}, + {"api_based_extension_id": 17}, + {"api_based_extension_id": []}, + {"api_based_extension_id": [_EXTENSION_ID]}, + {"api_based_extension_id": {}}, + {"api_based_extension_id": {"id": _EXTENSION_ID}}, +) class _Outbound: @@ -107,6 +125,21 @@ def outbound(lookup_events: list[str]) -> _Outbound: return _Outbound(lookup_events) +@pytest.fixture +def lookup_queries(sqlite_engine: Engine) -> Iterator[list[str]]: + """Record real SQL execution separately from connection ownership events.""" + queries: list[str] = [] + + def before_cursor_execute(*_args: object) -> None: + queries.append("query") + + event.listen(sqlite_engine, "before_cursor_execute", before_cursor_execute) + try: + yield queries + finally: + event.remove(sqlite_engine, "before_cursor_execute", before_cursor_execute) + + @pytest.fixture def service(sqlite_session_factory: sessionmaker[Session], outbound: _Outbound) -> APIModerationService: return APIModerationService( @@ -117,10 +150,13 @@ def service(sqlite_session_factory: sessionmaker[Session], outbound: _Outbound) ) -def _moderate(service: APIModerationService, raw: Mapping[str, object] | None, direction: str) -> object: +def _moderate( + service: APIModerationService, config: APIModerationConfig | None, direction: Literal["inputs", "outputs"] +) -> object: + """Exercise either runtime operation with complete authored settings or no config.""" if direction == "inputs": - return service.moderate_inputs(_TENANT_ID, "test-app-id", raw, {"q": "a"}, "hello") - return service.moderate_outputs(_TENANT_ID, "test-app-id", raw, "hello world") + return service.moderate_inputs(_TENANT_ID, "test-app-id", config, {"q": "a"}, "hello") + return service.moderate_outputs(_TENANT_ID, "test-app-id", config, "hello world") def test_moderation_input_params() -> None: @@ -142,35 +178,33 @@ def test_moderation_output_params() -> None: ModerationOutputParams.model_validate({}) +@pytest.mark.parametrize(("inputs_enabled", "outputs_enabled"), [(True, True), (True, False), (False, True)]) def test_validate_config_success( - service: APIModerationService, api_config: APIModerationConfig, lookup_events: list[str] + service: APIModerationService, + api_config: APIModerationConfig, + lookup_events: list[str], + inputs_enabled: bool, + outputs_enabled: bool, ) -> None: + """Each valid combination permits one scoped read and no outbound work.""" + api_config["inputs_config"]["enabled"] = inputs_enabled + api_config["outputs_config"]["enabled"] = outputs_enabled service.validate_config(_TENANT_ID, api_config) assert lookup_events == ["checkout", "checkin"] -@pytest.mark.parametrize( - ("config", "message"), - [ - ({}, "inputs_config must be a dict"), - ({"inputs_config": [], "outputs_config": []}, "inputs_config must be a dict"), - ({"inputs_config": {}}, "outputs_config must be a dict"), - ( - {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, - "At least one of inputs_config or outputs_config must be enabled", - ), - ( - {"inputs_config": {"enabled": True}, "outputs_config": {"enabled": True}}, - "api_based_extension_id is required", - ), - ], -) +@pytest.mark.parametrize("config", [{}, {"inputs_config": [], "outputs_config": []}, {"inputs_config": {}}]) def test_validate_config_rejects_invalid_config_before_lookup( - service: APIModerationService, config: dict[str, object], message: str, lookup_events: list[str] + service: APIModerationService, + config: dict[str, JsonValue], + lookup_events: list[str], + lookup_queries: list[str], ) -> None: - with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): + """Raw malformed forms fail validation before acquiring or querying a connection.""" + with pytest.raises(ValidationError): service.validate_config(_TENANT_ID, config) assert lookup_events == [] + assert lookup_queries == [] @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) @@ -186,11 +220,12 @@ def test_validate_config_extension_not_found( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) def test_enabled_moderation_releases_connection_before_external_io( service: APIModerationService, - direction: str, + direction: Literal["inputs", "outputs"], api_config: APIModerationConfig, lookup_events: list[str], outbound: _Outbound, ) -> None: + """Each operation passes the validated payload onward after its read session closes.""" if direction == "inputs": outbound.response = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} expected = {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"} @@ -203,18 +238,16 @@ def test_enabled_moderation_releases_connection_before_external_io( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) -@pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID, None]) +@pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) def test_enabled_moderation_extension_not_found( service: APIModerationService, - direction: str, - extension_id: str | None, + direction: Literal["inputs", "outputs"], + extension_id: str, api_config: APIModerationConfig, lookup_events: list[str], ) -> None: - if extension_id is None: - del api_config["api_based_extension_id"] - else: - api_config["api_based_extension_id"] = extension_id + """Missing and foreign valid string IDs retain the scoped not-found failure.""" + api_config["api_based_extension_id"] = extension_id with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): _moderate(service, api_config, direction) assert lookup_events == ["checkout", "checkin"] @@ -222,8 +255,12 @@ def test_enabled_moderation_extension_not_found( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) def test_disabled_moderation_skips_lookup( - service: APIModerationService, direction: str, api_config: APIModerationConfig, lookup_events: list[str] + service: APIModerationService, + direction: Literal["inputs", "outputs"], + api_config: APIModerationConfig, + lookup_events: list[str], ) -> None: + """A disabled authored direction returns the established result without a lookup.""" if direction == "inputs": api_config["inputs_config"] = {"enabled": False} else: @@ -238,8 +275,9 @@ def test_disabled_moderation_skips_lookup( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) def test_moderation_without_config_skips_lookup( - service: APIModerationService, direction: str, lookup_events: list[str] + service: APIModerationService, direction: Literal["inputs", "outputs"], lookup_events: list[str] ) -> None: + """Absent runtime config retains its explicit error before persistence access.""" with pytest.raises(ValueError, match=r"^The config is not set\.$"): _moderate(service, None, direction) assert lookup_events == [] @@ -276,9 +314,10 @@ def test_external_failure_preserves_identity_after_checkin( api_config: APIModerationConfig, outbound: _Outbound, lookup_events: list[str], - direction: str, - stage: str, + direction: Literal["inputs", "outputs"], + stage: Literal["decrypt", "request"], ) -> None: + """Original decrypt and request failures propagate after the connection is returned.""" failure = RuntimeError(f"{stage} failed") outbound.failure = (stage, failure) with pytest.raises(RuntimeError) as exc_info: @@ -290,36 +329,321 @@ def test_external_failure_preserves_identity_after_checkin( assert lookup_events == expected -@pytest.mark.parametrize("value", ["yes", 1, [False]]) -def test_non_boolean_truthiness_is_preserved( - service: APIModerationService, api_config: APIModerationConfig, value: object, lookup_events: list[str] +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("validation", ["runtime", "form"]) +@pytest.mark.parametrize("value", ["yes", "false", "", 0, 1, [], [False], {}, {"enabled": True}, None]) +def test_non_boolean_flags_are_rejected_before_lookup( + service: APIModerationService, + direction: Literal["inputs", "outputs"], + validation: Literal["runtime", "form"], + value: JsonValue, + lookup_events: list[str], + lookup_queries: list[str], ) -> None: - api_config["inputs_config"] = {"enabled": value} - service.moderate_inputs(_TENANT_ID, "app", api_config, {}) - assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + """Only actual boolean flags enter runtime or form execution.""" + raw: dict[str, JsonValue] = { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": True}, + "api_based_extension_id": _EXTENSION_ID, + } + raw[f"{direction}_config"] = {"enabled": value} + if validation == "form": + with pytest.raises(ValidationError): + service.validate_config(_TENANT_ID, raw) + elif direction == "inputs": + with pytest.raises(ValidationError): + service.moderate_inputs(_TENANT_ID, "app", raw, {}) + else: + with pytest.raises(ValidationError): + service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert lookup_events == [] + assert lookup_queries == [] +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("validation", ["runtime", "form"]) @pytest.mark.parametrize("selected", [None, [], "invalid", 1, {}]) -def test_selected_malformed_direction_retains_native_error( - service: APIModerationService, selected: object, lookup_events: list[str] +def test_malformed_direction_is_rejected_before_lookup( + service: APIModerationService, + direction: Literal["inputs", "outputs"], + validation: Literal["runtime", "form"], + selected: JsonValue, + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Malformed selected settings fail before SQL or outbound capabilities.""" + raw: dict[str, JsonValue] = { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": True}, + "api_based_extension_id": _EXTENSION_ID, + } + raw[f"{direction}_config"] = selected + if validation == "form": + with pytest.raises(ValidationError): + service.validate_config(_TENANT_ID, raw) + elif direction == "inputs": + with pytest.raises(ValidationError): + service.moderate_inputs(_TENANT_ID, "app", raw, {}) + else: + with pytest.raises(ValidationError): + service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert lookup_events == [] + assert lookup_queries == [] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("validation", ["runtime", "form"]) +def test_missing_direction_is_rejected_before_lookup( + service: APIModerationService, + direction: Literal["inputs", "outputs"], + validation: Literal["runtime", "form"], + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Missing selected settings are validation failures with no persistence work.""" + opposite = "outputs_config" if direction == "inputs" else "inputs_config" + raw: dict[str, JsonValue] = {opposite: {"enabled": True}, "api_based_extension_id": _EXTENSION_ID} + if validation == "form": + with pytest.raises(ValidationError): + service.validate_config(_TENANT_ID, raw) + elif direction == "inputs": + with pytest.raises(ValidationError): + service.moderate_inputs(_TENANT_ID, "app", raw, {}) + else: + with pytest.raises(ValidationError): + service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert lookup_events == [] + assert lookup_queries == [] + + +@pytest.mark.parametrize("operation", ["inputs", "outputs", "form"]) +@pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) +def test_invalid_extension_id_is_rejected_before_lookup( + service: APIModerationService, + operation: Literal["inputs", "outputs", "form"], + extension_config: dict[str, JsonValue], + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Enabled operations and forms reject missing, empty or non-string IDs before I/O.""" + raw: dict[str, JsonValue] = { + "inputs_config": {"enabled": True}, + "outputs_config": {"enabled": True}, + **extension_config, + } + if operation == "form": + with pytest.raises(ValidationError): + service.validate_config(_TENANT_ID, raw) + elif operation == "inputs": + with pytest.raises(ValidationError): + service.moderate_inputs(_TENANT_ID, "app", raw, {}) + else: + with pytest.raises(ValidationError): + service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert lookup_events == [] + assert lookup_queries == [] + + +@pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) +def test_both_disabled_form_precedes_extension_id_validation( + service: APIModerationService, + extension_config: dict[str, JsonValue], + lookup_events: list[str], + lookup_queries: list[str], ) -> None: - raw = {"inputs_config": selected} - with pytest.raises((KeyError, TypeError)): - service.moderate_inputs(_TENANT_ID, "app", raw, {}) + """Two false flags retain their business error even with an invalid or absent ID.""" + raw: dict[str, JsonValue] = { + "inputs_config": {"enabled": False}, + "outputs_config": {"enabled": False}, + **extension_config, + } + message = "At least one of inputs_config or outputs_config must be enabled" + with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): + service.validate_config(_TENANT_ID, raw) assert lookup_events == [] + assert lookup_queries == [] -def test_disabled_directions_ignore_opposite_malformed_values( - service: APIModerationService, lookup_events: list[str] +def test_form_parses_inputs_direction_before_outputs_direction( + service: APIModerationService, lookup_events: list[str], lookup_queries: list[str] +) -> None: + """The input direction's missing flag wins over malformed output settings.""" + raw: dict[str, JsonValue] = {"inputs_config": {}, "outputs_config": None} + with pytest.raises(ValidationError) as raised: + service.validate_config(_TENANT_ID, raw) + assert [(error["loc"], error["type"]) for error in raised.value.errors()] == [(("enabled",), "missing")] + assert lookup_events == [] + assert lookup_queries == [] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) +def test_disabled_direction_ignores_invalid_id_opposite_settings_and_payload( + service: APIModerationService, + direction: Literal["inputs", "outputs"], + extension_config: dict[str, JsonValue], + lookup_events: list[str], + lookup_queries: list[str], ) -> None: - assert parse_direction({"inputs_config": {"enabled": False}, "outputs_config": None}, "inputs_config") == ( - DisabledDirection() + """A false selected flag skips invalid ID, opposite settings and input values.""" + selected: Literal["inputs_config", "outputs_config"] = ( + "inputs_config" if direction == "inputs" else "outputs_config" ) - for direction in ("inputs", "outputs"): - assert _moderate( - service, {"inputs_config": {"enabled": False}, "outputs_config": {"enabled": False}}, direction - ) == {"flagged": False, "action": "direct_output", "preset_response": ""} + opposite = "outputs_config" if direction == "inputs" else "inputs_config" + raw: dict[str, JsonValue] = {selected: {"enabled": False}, opposite: None, **extension_config} + assert parse_direction(raw, selected) == DisabledDirection() + if direction == "inputs": + result = service.moderate_inputs(_TENANT_ID, "app", raw, {"unsupported": object()}) + else: + result = service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert result == {"flagged": False, "action": "direct_output", "preset_response": ""} + assert lookup_events == [] + assert lookup_queries == [] + + +@pytest.mark.parametrize("direction", ["inputs", "outputs"]) +@pytest.mark.parametrize("opposite_value", [None, [], "invalid", 1, {}, {"enabled": "yes"}]) +def test_enabled_direction_ignores_malformed_opposite_settings( + service: APIModerationService, + direction: Literal["inputs", "outputs"], + opposite_value: JsonValue, + lookup_events: list[str], + outbound: _Outbound, +) -> None: + """An enabled runtime selection reads only its own direction settings.""" + selected = "inputs_config" if direction == "inputs" else "outputs_config" + opposite = "outputs_config" if direction == "inputs" else "inputs_config" + raw: dict[str, JsonValue] = { + selected: {"enabled": True}, + opposite: opposite_value, + "api_based_extension_id": _EXTENSION_ID, + } + if direction == "inputs": + result = service.moderate_inputs(_TENANT_ID, "app", raw, {}) + else: + result = service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + assert result is outbound.response + assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + + +@pytest.mark.parametrize("extension_id", ["custom-extension-key", " ", _EXTENSION_ID.upper()]) +def test_direction_selection_preserves_string_ids_and_ignores_unknown_keys(extension_id: str) -> None: + """Nonempty strings are kept exactly and unrelated config fields are ignored.""" + raw: dict[str, JsonValue] = { + "inputs_config": {"enabled": True, "unknown": [1, True]}, + "api_based_extension_id": extension_id, + "unknown": None, + } + assert parse_direction(raw, "inputs_config") == EnabledDirection(extension_id) + + +@pytest.mark.parametrize("inputs", [{"invalid": object()}, {"invalid": [object()]}, {"invalid": {"nested": object()}}]) +def test_enabled_input_payload_rejects_unsupported_values_before_lookup( + service: APIModerationService, + api_config: APIModerationConfig, + inputs: dict[str, object], + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Arbitrary objects, including nested ones, fail admission before any I/O.""" + with pytest.raises(ValidationError): + service.moderate_inputs(_TENANT_ID, "app", api_config, inputs) assert lookup_events == [] + assert lookup_queries == [] + + +def test_input_domain_survives_sqlite_and_gateway_serialization( + api_config: APIModerationConfig, + sqlite_session_factory: sessionmaker[Session], + outbound: _Outbound, + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Real files and dynamic JSON retain their values through admission, SQL and the wire gateway.""" + attachment = File( + file_id="66666666-6666-4666-8666-666666666666", + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.com/input.pdf", + filename="input.pdf", + extension=".pdf", + mime_type="application/pdf", + size=12, + ) + file_shaped_json: dict[str, JsonValue] = { + "dify_model_identity": "__dify__file__", + "id": "77777777-7777-4777-8777-777777777777", + "type": "document", + "transfer_method": "remote_url", + "remote_url": "https://example.com/ordinary.json", + "reference": None, + "filename": "ordinary.json", + "extension": ".json", + "mime_type": "application/json", + "size": 4, + "related_id": None, + "url": "https://example.com/ordinary.json", + "ordinary_json": {"keep": [1, True]}, + } + values: dict[str, MessageInputValue] = { + "任意用户变量": "你好", + "empty_text": "", + "nothing": None, + "empty_object": {}, + "empty_list": [], + "number": 1.5, + "checked": True, + "nested": {"object": {"flags": [1, True], "null": None}}, + "mixed": [1, True], + "file": attachment, + "files": [attachment], + "file_json": file_shaped_json, + } + response = {"flagged": False, "action": "direct_output", "preset_response": ""} + calls: list[tuple[str, str, APIBasedExtensionPoint, dict[str, object]]] = [] + admitted: list[ModerationInputParams] = [] + + def request(endpoint: str, key: str, point: APIBasedExtensionPoint, params: dict[str, object]) -> object: + assert lookup_events == ["checkout", "checkin", "decrypt"] + lookup_events.append("request") + calls.append((endpoint, key, point, params)) + return response + + gateway = APIModerationGateway(request=request) + + def request_inputs(endpoint: str, key: str, params: ModerationInputParams) -> object: + admitted.append(params) + return gateway.inputs(endpoint, key, params) + + service = APIModerationService( + find_extension=APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension, + decrypt_key=outbound.decrypt, + request_inputs=request_inputs, + request_outputs=gateway.outputs, + ) + assert service.moderate_inputs(_TENANT_ID, "test-app-id", api_config, values, "hello") is response + assert len(admitted) == 1 + params = admitted[0] + assert params.inputs == values + assert params.inputs["file"] is attachment + files = params.inputs["files"] + assert isinstance(files, list) + assert len(files) == 1 + assert files[0] is attachment + assert isinstance(params.inputs["file_json"], dict) + assert params.inputs["file_json"] == file_shaped_json + mixed = params.inputs["mixed"] + assert isinstance(mixed, list) + assert type(mixed[0]) is int + assert type(mixed[1]) is bool + expected = { + "app_id": "test-app-id", + "inputs": {**values, "file": attachment.model_dump(), "files": [attachment.model_dump()]}, + "query": "hello", + } + assert calls == [(_ENDPOINT, "decrypted-key", APIBasedExtensionPoint.APP_MODERATION_INPUT, expected)] + assert lookup_events == ["checkout", "checkin", "decrypt", "request"] + assert lookup_queries == ["query"] def test_service_uses_explicit_database_instead_of_global( From 9fd8f7e6f0e970f9c807b23701b8dda79d5d01c7 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 15:14:55 +0800 Subject: [PATCH 08/12] test(api): align moderation transport fixture with main types --- .../test_api_based_extension_requestor.py | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py index b7d4b01b0c6b7e..094fc0ac0a61c3 100644 --- a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py +++ b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py @@ -8,13 +8,20 @@ from models.api_based_extension import APIBasedExtensionPoint from services.api_based_extension_adapters import request_api_based_extension +RequestHandler = Callable[[httpx.Request], httpx.Response] +InstalledClient = tuple[ + list[httpx.Request], + list[tuple[dict[str, httpx.BaseTransport] | None, httpx.Timeout]], +] +InstallClient = Callable[[RequestHandler], InstalledClient] + @pytest.fixture -def install_client(monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]): +def install_client(monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]) -> InstallClient: config_overrides(SSRF_PROXY_HTTP_URL=None, SSRF_PROXY_HTTPS_URL=None) client_type = httpx.Client - def install(handler: Callable[[httpx.Request], httpx.Response]): + def install(handler: RequestHandler) -> InstalledClient: requests: list[httpx.Request] = [] options: list[tuple[dict[str, httpx.BaseTransport] | None, httpx.Timeout]] = [] @@ -32,7 +39,7 @@ def client(*, mounts: dict[str, httpx.BaseTransport] | None, timeout: httpx.Time return install -def test_request_success(install_client): +def test_request_success(install_client: InstallClient) -> None: requests, _ = install_client(lambda _: httpx.Response(200, json={"result": "success"})) requestor = APIBasedExtensionRequestor(api_endpoint="http://example.com", api_key="test_key") result = requestor.request(APIBasedExtensionPoint.PING, {"foo": "bar"}) @@ -58,7 +65,7 @@ def test_request_success(install_client): ], ) def test_request_adapter_preserves_moderation_wire_contract( - install_client, point: APIBasedExtensionPoint, params: dict[str, object] + install_client: InstallClient, point: APIBasedExtensionPoint, params: dict[str, object] ) -> None: """Use the fixture's in-process transport for each moderation point and payload. @@ -81,8 +88,8 @@ def test_request_adapter_preserves_moderation_wire_contract( def test_request_with_ssrf_proxy( - install_client, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] -): + install_client: InstallClient, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] +) -> None: config_overrides(SSRF_PROXY_HTTP_URL="http://proxy:8080", SSRF_PROXY_HTTPS_URL="https://proxy:8081") _, options = install_client(lambda _: httpx.Response(200, json={"result": "success"})) proxies: list[str] = [] @@ -105,7 +112,9 @@ def transport(*, proxy: str) -> httpx.MockTransport: assert timeout is requestor.timeout -def test_request_with_only_one_proxy_config(install_client, config_overrides: Callable[..., None]): +def test_request_with_only_one_proxy_config( + install_client: InstallClient, config_overrides: Callable[..., None] +) -> None: config_overrides(SSRF_PROXY_HTTP_URL="http://proxy:8080", SSRF_PROXY_HTTPS_URL=None) _, options = install_client(lambda _: httpx.Response(200, json={"result": "success"})) requestor = APIBasedExtensionRequestor(api_endpoint="http://example.com", api_key="test_key") @@ -115,7 +124,7 @@ def test_request_with_only_one_proxy_config(install_client, config_overrides: Ca assert options[0][0] is None -def test_request_timeout(install_client): +def test_request_timeout(install_client: InstallClient) -> None: original = httpx.TimeoutException("timeout") def fail(_request: httpx.Request) -> httpx.Response: @@ -129,7 +138,7 @@ def fail(_request: httpx.Request) -> httpx.Response: assert exc_info.value.__cause__ is original -def test_request_connection_error(install_client): +def test_request_connection_error(install_client: InstallClient) -> None: original = httpx.RequestError("error") def fail(_request: httpx.Request) -> httpx.Response: @@ -143,14 +152,14 @@ def fail(_request: httpx.Request) -> httpx.Response: assert exc_info.value.__cause__ is original -def test_request_error_status_code(install_client): +def test_request_error_status_code(install_client: InstallClient) -> None: install_client(lambda _: httpx.Response(404, text="Not Found")) requestor = APIBasedExtensionRequestor(api_endpoint="http://example.com", api_key="test_key") with pytest.raises(ValueError, match="request error, status_code: 404, content: Not Found"): requestor.request(APIBasedExtensionPoint.PING, {}) -def test_request_error_status_code_long_content(install_client): +def test_request_error_status_code_long_content(install_client: InstallClient) -> None: install_client(lambda _: httpx.Response(500, text="A" * 200)) requestor = APIBasedExtensionRequestor(api_endpoint="http://example.com", api_key="test_key") expected_content = "A" * 100 From 7da40c9af8a600be90e2521b8d2d3d555c0021c3 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 16:42:46 +0800 Subject: [PATCH 09/12] test(api): clarify moderation admission and type keyword fixtures --- api/core/moderation/factory.py | 8 +++++++- api/tests/unit_tests/core/moderation/test_factory.py | 11 ++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/api/core/moderation/factory.py b/api/core/moderation/factory.py index 140eb39a1d0ce2..fec097ff76f9ff 100644 --- a/api/core/moderation/factory.py +++ b/api/core/moderation/factory.py @@ -14,7 +14,13 @@ @dataclass(frozen=True, slots=True) class APIModerationCallbacks: - """Required API capabilities bound by the composition root to one Flask app.""" + """Service admission methods bound by the composition root to one Flask app. + + Config mappings contain unparsed persisted or form data. The bound methods + parse the selected operation into typed settings before lookup or outbound I/O. + Runtime admission inspects only its direction; disabled settings skip ID and + payload validation. Complete authored settings are not required at this boundary. + """ validate_config: Callable[[str, Mapping[str, object]], None] moderate_inputs: Callable[[str, str, Mapping[str, object] | None, dict[str, object], str], JsonValue] diff --git a/api/tests/unit_tests/core/moderation/test_factory.py b/api/tests/unit_tests/core/moderation/test_factory.py index 5c52ed11b7361b..24c84abe283a0a 100644 --- a/api/tests/unit_tests/core/moderation/test_factory.py +++ b/api/tests/unit_tests/core/moderation/test_factory.py @@ -10,6 +10,7 @@ from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory from extensions.ext_code_based_extension import code_based_extension +from models.agent_config_entities import AgentModerationIOConfig, AgentModerationProviderConfig from models.api_based_extension import APIBasedExtension from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_moderation_service import ( @@ -263,11 +264,11 @@ def test_factory_delegates_to_extension(self) -> None: def test_factory_validate_config_delegates(self) -> None: """Run the actual provider's form rules through factory class validation.""" - valid: dict[str, object] = { - "inputs_config": {"enabled": True, "preset_response": "Blocked"}, - "outputs_config": {"enabled": False}, - "keywords": "bad", - } + valid = AgentModerationProviderConfig( + inputs_config=AgentModerationIOConfig(enabled=True, preset_response="Blocked"), + outputs_config=AgentModerationIOConfig(enabled=False), + keywords="bad", + ).model_dump(exclude_none=True) ModerationFactory.validate_config("keywords", _TENANT_ID, valid) invalid = dict(valid) del invalid["keywords"] From aa446f3f6ea560362774eb04664adc27f6ecacd7 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Tue, 17 Nov 2026 17:33:46 +0800 Subject: [PATCH 10/12] refactor(api): pass parsed moderation settings to services --- api/.importlinter | 2 +- api/core/moderation/factory.py | 24 +- api/domain/moderation/__init__.py | 0 api/domain/moderation/api_config.py | 70 ++++++ api/services/api_moderation_service.py | 97 ++------ .../core/moderation/test_factory.py | 31 ++- .../test_api_based_extension_adapters.py | 31 ++- .../services/test_api_moderation_service.py | 212 ++++++++++-------- 8 files changed, 270 insertions(+), 197 deletions(-) create mode 100644 api/domain/moderation/__init__.py create mode 100644 api/domain/moderation/api_config.py diff --git a/api/.importlinter b/api/.importlinter index 0ccf7fe8e568e0..a4e0abcca55519 100644 --- a/api/.importlinter +++ b/api/.importlinter @@ -946,7 +946,7 @@ forbidden_modules = werkzeug [importlinter:contract:api-moderation-application-boundary] -name = API moderation owns framework-neutral parsing and orchestration +name = API moderation owns framework-neutral orchestration of admitted settings type = forbidden source_modules = services.api_moderation_service diff --git a/api/core/moderation/factory.py b/api/core/moderation/factory.py index fec097ff76f9ff..138baffbea0a2f 100644 --- a/api/core/moderation/factory.py +++ b/api/core/moderation/factory.py @@ -7,6 +7,7 @@ from core.extension.extensible import ExtensionModule from core.moderation.base import Moderation, ModerationInputsResult, ModerationOutputsResult +from domain.moderation.api_config import DisabledDirection, EnabledDirection, parse_direction, parse_form from extensions.ext_code_based_extension import code_based_extension API_MODERATION_EXTENSION_KEY = "api_moderation" @@ -14,17 +15,15 @@ @dataclass(frozen=True, slots=True) class APIModerationCallbacks: - """Service admission methods bound by the composition root to one Flask app. + """Application operations bound by the composition root to one Flask app. - Config mappings contain unparsed persisted or form data. The bound methods - parse the selected operation into typed settings before lookup or outbound I/O. - Runtime admission inspects only its direction; disabled settings skip ID and - payload validation. Complete authored settings are not required at this boundary. + Configuration is parsed before dispatch. Operations receive an admitted + selection, never raw settings, and preserve disabled payload bypass and I/O order. """ - validate_config: Callable[[str, Mapping[str, object]], None] - moderate_inputs: Callable[[str, str, Mapping[str, object] | None, dict[str, object], str], JsonValue] - moderate_outputs: Callable[[str, str, Mapping[str, object] | None, str], JsonValue] + validate_config: Callable[[str, EnabledDirection], None] + moderate_inputs: Callable[[str, str, DisabledDirection | EnabledDirection, dict[str, object], str], JsonValue] + moderate_outputs: Callable[[str, str, DisabledDirection | EnabledDirection, str], JsonValue] @dataclass(slots=True) @@ -80,7 +79,8 @@ def validate_config(cls, name: str, tenant_id: str, config: dict[str, Any]): :return: """ if name == "api": - _api_callbacks().validate_config(tenant_id, config) + callbacks = _api_callbacks() + callbacks.validate_config(tenant_id, parse_form(config)) else: _moderation_class(name).validate_config(tenant_id, config) @@ -102,7 +102,7 @@ def moderation_for_inputs(self, inputs: dict[str, Any], query: str = "") -> Mode if provider.callbacks is None: provider.callbacks = _api_callbacks() result = provider.callbacks.moderate_inputs( - provider.tenant_id, provider.app_id, provider.config, inputs, query + provider.tenant_id, provider.app_id, parse_direction(provider.config, "inputs_config"), inputs, query ) return ModerationInputsResult.model_validate(result) return provider.moderation_for_inputs(inputs, query) @@ -123,6 +123,8 @@ def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: if isinstance(provider, _APIModeration): if provider.callbacks is None: provider.callbacks = _api_callbacks() - result = provider.callbacks.moderate_outputs(provider.tenant_id, provider.app_id, provider.config, text) + result = provider.callbacks.moderate_outputs( + provider.tenant_id, provider.app_id, parse_direction(provider.config, "outputs_config"), text + ) return ModerationOutputsResult.model_validate(result) return provider.moderation_for_outputs(text) diff --git a/api/domain/moderation/__init__.py b/api/domain/moderation/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/api/domain/moderation/api_config.py b/api/domain/moderation/api_config.py new file mode 100644 index 00000000000000..bddc79816b9ecc --- /dev/null +++ b/api/domain/moderation/api_config.py @@ -0,0 +1,70 @@ +"""Parse untrusted API moderation settings into one operation's configuration. + +Runtime admission inspects only the selected direction. Disabled selections do +not require a valid extension ID. Form admission checks both directions in order. +""" + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Annotated, Literal, TypedDict + +from pydantic import Field, TypeAdapter + + +class APIModerationDirectionConfig(TypedDict): + """A configured direction explicitly chooses a boolean enable state.""" + + enabled: bool + + +class APIModerationConfig(TypedDict): + """Complete authored settings, distinct from untrusted runtime input.""" + + inputs_config: APIModerationDirectionConfig + outputs_config: APIModerationDirectionConfig + api_based_extension_id: str + + +_direction_adapter = TypeAdapter(APIModerationDirectionConfig) +_extension_id_adapter = TypeAdapter(Annotated[str, Field(strict=True, min_length=1)]) + + +@dataclass(frozen=True, slots=True) +class DisabledDirection: + """The selected direction requires no lookup or outbound work.""" + + +@dataclass(frozen=True, slots=True) +class EnabledDirection: + """The selected enabled direction carries its parsed, nonempty lookup key.""" + + extension_id: str + + +def parse_direction( + raw: Mapping[str, object] | None, direction: Literal["inputs_config", "outputs_config"] +) -> DisabledDirection | EnabledDirection: + """Admit one raw runtime direction without inspecting the opposite direction. + + Missing config raises ValueError; malformed selected settings raise + ValidationError. Disabled settings return before ID validation. No I/O occurs. + """ + if raw is None: + raise ValueError("The config is not set.") + selected = _direction_adapter.validate_python(raw.get(direction), strict=True) + if not selected["enabled"]: + return DisabledDirection() + return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) + + +def parse_form(raw: Mapping[str, object]) -> EnabledDirection: + """Admit both form directions, require one enabled, then parse the ID without I/O. + + Malformed settings raise ValidationError. Two disabled directions retain their + business error before ID validation, including when the ID is absent or invalid. + """ + inputs_config = _direction_adapter.validate_python(raw.get("inputs_config"), strict=True) + outputs_config = _direction_adapter.validate_python(raw.get("outputs_config"), strict=True) + if not inputs_config["enabled"] and not outputs_config["enabled"]: + raise ValueError("At least one of inputs_config or outputs_config must be enabled") + return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) diff --git a/api/services/api_moderation_service.py b/api/services/api_moderation_service.py index 5d908426d34323..880f9e1190e383 100644 --- a/api/services/api_moderation_service.py +++ b/api/services/api_moderation_service.py @@ -1,37 +1,18 @@ """API moderation with explicit, workspace-scoped persistence and outbound capabilities. -Complete form settings require both directions and a string extension ID. Runtime -selection validates only its direction, and enabled requests are validated before I/O. +Operations receive parsed direction selections. Enabled requests validate their +payloads before I/O; disabled selections perform no lookup or outbound work. """ from collections.abc import Callable, Mapping -from dataclasses import dataclass -from typing import Annotated, Literal, TypedDict -from pydantic import BaseModel, Field, InstanceOf, JsonValue, TypeAdapter +from pydantic import BaseModel, Field, InstanceOf, JsonValue +from domain.moderation.api_config import DisabledDirection, EnabledDirection from graphon.file import File from services.api_based_extension_application_service import APIBasedExtensionRecord -class APIModerationDirectionConfig(TypedDict): - """A configured direction explicitly chooses a boolean enable state.""" - - enabled: bool - - -class APIModerationConfig(TypedDict): - """Complete authored settings; partial runtime values enter through raw mappings.""" - - inputs_config: APIModerationDirectionConfig - outputs_config: APIModerationDirectionConfig - api_based_extension_id: str - - -_direction_adapter = TypeAdapter(APIModerationDirectionConfig) -_extension_id_adapter = TypeAdapter(Annotated[str, Field(strict=True, min_length=1)]) - - class ModerationInputParams(BaseModel): """Keep JSON mappings as JSON and admit file variants only as existing File instances.""" @@ -45,47 +26,6 @@ class ModerationOutputParams(BaseModel): text: str -@dataclass(frozen=True, slots=True) -class DisabledDirection: - """The selected direction requires no lookup or outbound work.""" - - -@dataclass(frozen=True, slots=True) -class EnabledDirection: - """The selected enabled direction has a validated, nonempty string lookup key.""" - - extension_id: str - - -def parse_direction( - raw: Mapping[str, object] | None, direction: Literal["inputs_config", "outputs_config"] -) -> DisabledDirection | EnabledDirection: - """Parse one runtime direction without inspecting the opposite direction. - - Missing config raises ValueError; malformed selected settings raise - ValidationError. Disabled settings return before ID validation. No I/O occurs. - """ - if raw is None: - raise ValueError("The config is not set.") - selected = _direction_adapter.validate_python(raw.get(direction), strict=True) - if not selected["enabled"]: - return DisabledDirection() - return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) - - -def _parse_form(raw: Mapping[str, object]) -> EnabledDirection: - """Validate both directions, require one enabled, then parse the ID without I/O. - - Malformed settings raise ValidationError. Two disabled directions retain their - business error before ID validation, including when the ID is absent or invalid. - """ - inputs_config = _direction_adapter.validate_python(raw.get("inputs_config"), strict=True) - outputs_config = _direction_adapter.validate_python(raw.get("outputs_config"), strict=True) - if not inputs_config["enabled"] and not outputs_config["enabled"]: - raise ValueError("At least one of inputs_config or outputs_config must be enabled") - return EnabledDirection(_extension_id_adapter.validate_python(raw.get("api_based_extension_id"))) - - class APIModerationService: """Own API settings and release persistence before decryption and requests. @@ -107,30 +47,28 @@ def __init__( self._request_inputs = request_inputs self._request_outputs = request_outputs - def validate_config(self, tenant_id: str, raw: Mapping[str, object]) -> None: - """Require valid form settings and an owned extension without outbound I/O. + def validate_config(self, tenant_id: str, selection: EnabledDirection) -> None: + """Require an owned extension for admitted form settings without outbound I/O. - Malformed settings raise ValidationError; both-disabled settings or an - absent owned row raise ValueError. Lookup failures propagate after session - cleanup. Successful validation changes no state. + An absent owned row raises ValueError. Lookup failures propagate after + session cleanup. Successful validation changes no state. """ - self._require_extension(tenant_id, _parse_form(raw).extension_id) + self._require_extension(tenant_id, selection.extension_id) def moderate_inputs( self, tenant_id: str, app_id: str, - raw: Mapping[str, object] | None, + selection: DisabledDirection | EnabledDirection, inputs: Mapping[str, object], query: str = "", ) -> JsonValue: """Return the disabled result or raw input response for facade validation. - Raw mappings admit dynamic variable names with JSON, File or list[File] - values. Enabled settings and payloads must validate before lookup. Disabled - settings skip payload validation and all I/O. Dependency failures propagate. + The selection is already admitted. Input mappings admit dynamic variable + names with JSON, File or list[File] values. Enabled payloads validate before + lookup; disabled selections skip validation and I/O. Dependency errors propagate. """ - selection = parse_direction(raw, "inputs_config") if isinstance(selection, DisabledDirection): return {"flagged": False, "action": "direct_output", "preset_response": ""} params = ModerationInputParams.model_validate({"app_id": app_id, "inputs": inputs, "query": query}) @@ -138,14 +76,15 @@ def moderate_inputs( key = self._decrypt_key(tenant_id, extension.api_key) return self._request_inputs(extension.api_endpoint, key, params) - def moderate_outputs(self, tenant_id: str, app_id: str, raw: Mapping[str, object] | None, text: str) -> JsonValue: + def moderate_outputs( + self, tenant_id: str, app_id: str, selection: DisabledDirection | EnabledDirection, text: str + ) -> JsonValue: """Return the disabled result or raw output response for facade validation. - Enabled settings and request parameters validate before lookup. Disabled - settings skip payload validation and all I/O. Lookup, decrypt and request + The selection is already admitted. Enabled request parameters validate before + lookup; disabled selections skip validation and I/O. Lookup, decrypt and request failures propagate unchanged in that order. """ - selection = parse_direction(raw, "outputs_config") if isinstance(selection, DisabledDirection): return {"flagged": False, "action": "direct_output", "preset_response": ""} params = ModerationOutputParams(app_id=app_id, text=text) diff --git a/api/tests/unit_tests/core/moderation/test_factory.py b/api/tests/unit_tests/core/moderation/test_factory.py index 24c84abe283a0a..095430cb4fdf25 100644 --- a/api/tests/unit_tests/core/moderation/test_factory.py +++ b/api/tests/unit_tests/core/moderation/test_factory.py @@ -9,12 +9,12 @@ from core.extension.extensible import ExtensionModule from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory +from domain.moderation.api_config import APIModerationConfig from extensions.ext_code_based_extension import code_based_extension from models.agent_config_entities import AgentModerationIOConfig, AgentModerationProviderConfig from models.api_based_extension import APIBasedExtension from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_moderation_service import ( - APIModerationConfig, APIModerationService, ModerationInputParams, ModerationOutputParams, @@ -174,6 +174,35 @@ def test_api_factory_requires_root_bundle(moderation_app: Flask) -> None: ModerationFactory("api", "app", _TENANT_ID, {}).moderation_for_inputs({}) +def test_api_factory_reparses_settings_after_binding(moderation_app: Flask, requests: _Requests) -> None: + """Reusing callbacks must still admit the current settings for each operation.""" + config: APIModerationConfig = { + "inputs_config": {"enabled": False}, + "outputs_config": {"enabled": True}, + "api_based_extension_id": _EXTENSION_ID, + } + factory = ModerationFactory("api", "app", _TENANT_ID, dict(config)) + with moderation_app.app_context(): + assert factory.moderation_for_outputs("first") == ModerationOutputsResult( + flagged=True, action=ModerationAction.DIRECT_OUTPUT, preset_response="Blocked by API" + ) + assert len(requests.calls) == 2 + config["outputs_config"]["enabled"] = False + assert factory.moderation_for_outputs("second") == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert len(requests.calls) == 2 + + +def test_api_factory_keeps_binding_after_failed_admission(moderation_app: Flask, requests: _Requests) -> None: + """A failed first parse keeps the resolved app callbacks for later operations.""" + raw: dict[str, JsonValue] = {"outputs_config": {"enabled": "yes"}} + factory = ModerationFactory("api", "app", _TENANT_ID, raw) + with moderation_app.app_context(), pytest.raises(ValidationError): + factory.moderation_for_outputs("first") + raw["outputs_config"] = {"enabled": False} + assert factory.moderation_for_outputs("second") == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) + assert requests.calls == [] + + def test_api_factory_validation_uses_injected_real_repository(moderation_app: Flask, requests: _Requests) -> None: """Validate owned settings through the fixture's repository without outbound calls. diff --git a/api/tests/unit_tests/services/test_api_based_extension_adapters.py b/api/tests/unit_tests/services/test_api_based_extension_adapters.py index b6d703deada68e..8e1c2dcfe90224 100644 --- a/api/tests/unit_tests/services/test_api_based_extension_adapters.py +++ b/api/tests/unit_tests/services/test_api_based_extension_adapters.py @@ -1,3 +1,4 @@ +import json from typing import Literal from unittest.mock import MagicMock @@ -79,14 +80,19 @@ def request(endpoint: str, key: str, point: APIBasedExtensionPoint, params: dict if direction == "inputs": params = ModerationInputParams(app_id="app", inputs={"field": [1, True]}, query="hello") assert gateway.inputs("https://extension.example.test", "plaintext-key", params) is response - point = APIBasedExtensionPoint.APP_MODERATION_INPUT + expected_point = APIBasedExtensionPoint.APP_MODERATION_INPUT expected = {"app_id": "app", "inputs": {"field": [1, True]}, "query": "hello"} else: output_params = ModerationOutputParams(app_id="app", text="hello") assert gateway.outputs("https://extension.example.test", "plaintext-key", output_params) is response - point = APIBasedExtensionPoint.APP_MODERATION_OUTPUT + expected_point = APIBasedExtensionPoint.APP_MODERATION_OUTPUT expected = {"app_id": "app", "text": "hello"} - assert calls == [("https://extension.example.test", "plaintext-key", point, expected)] + assert len(calls) == 1 + endpoint, key, point, payload = calls[0] + assert (endpoint, key, point) == ("https://extension.example.test", "plaintext-key", expected_point) + assert json.dumps(payload, sort_keys=True, ensure_ascii=False) == json.dumps( + expected, sort_keys=True, ensure_ascii=False + ) def test_input_domain_serialization_preserves_files_and_json() -> None: @@ -131,12 +137,6 @@ def test_input_domain_serialization_preserves_files_and_json() -> None: def request(endpoint: str, key: str, point: APIBasedExtensionPoint, payload: dict[str, JsonValue]) -> JsonValue: calls.append((endpoint, key, point, payload)) - wire_inputs = payload["inputs"] - assert isinstance(wire_inputs, dict) - wire_mixed = wire_inputs["mixed"] - assert isinstance(wire_mixed, list) - assert type(wire_mixed[0]) is int - assert type(wire_mixed[1]) is bool return response assert APIModerationGateway(request=request).inputs("https://extension.example.test", "plaintext-key", params) is ( @@ -154,9 +154,16 @@ def request(endpoint: str, key: str, point: APIBasedExtensionPoint, payload: dic "inputs": {**values, "file": attachment.model_dump(), "files": [attachment.model_dump()]}, "query": "", } - assert calls == [ - ("https://extension.example.test", "plaintext-key", APIBasedExtensionPoint.APP_MODERATION_INPUT, expected) - ] + assert len(calls) == 1 + endpoint, key, point, payload = calls[0] + assert (endpoint, key, point) == ( + "https://extension.example.test", + "plaintext-key", + APIBasedExtensionPoint.APP_MODERATION_INPUT, + ) + assert json.dumps(payload, sort_keys=True, ensure_ascii=False) == json.dumps( + expected, sort_keys=True, ensure_ascii=False + ) @pytest.mark.parametrize("direction", ["inputs", "outputs"]) diff --git a/api/tests/unit_tests/services/test_api_moderation_service.py b/api/tests/unit_tests/services/test_api_moderation_service.py index eb10910697db80..d9c05edb1dccbb 100644 --- a/api/tests/unit_tests/services/test_api_moderation_service.py +++ b/api/tests/unit_tests/services/test_api_moderation_service.py @@ -1,25 +1,26 @@ +import json import re -from collections.abc import Iterator +from collections.abc import Iterator, Mapping from typing import Literal import pytest +from flask import Flask from pydantic import JsonValue, ValidationError from sqlalchemy import Engine, create_engine, event from sqlalchemy.orm import Session, sessionmaker +from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult +from core.moderation.factory import API_MODERATION_EXTENSION_KEY, APIModerationCallbacks, ModerationFactory +from domain.moderation.api_config import APIModerationConfig, DisabledDirection, EnabledDirection, parse_direction from graphon.file import File, FileTransferMethod, FileType from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint from models.base import TypeBase from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_based_extension_adapters import APIModerationGateway from services.api_moderation_service import ( - APIModerationConfig, APIModerationService, - DisabledDirection, - EnabledDirection, ModerationInputParams, ModerationOutputParams, - parse_direction, ) from services.entities.message_entities import MessageInputValue @@ -150,18 +151,44 @@ def service(sqlite_session_factory: sessionmaker[Session], outbound: _Outbound) ) +@pytest.fixture +def moderation_app(service: APIModerationService) -> Flask: + """Bind the observed real repository and outbound service without entering app context.""" + app = Flask(__name__) + app.extensions[API_MODERATION_EXTENSION_KEY] = APIModerationCallbacks( + service.validate_config, service.moderate_inputs, service.moderate_outputs + ) + return app + + def _moderate( - service: APIModerationService, config: APIModerationConfig | None, direction: Literal["inputs", "outputs"] + service: APIModerationService, + selection: DisabledDirection | EnabledDirection, + direction: Literal["inputs", "outputs"], ) -> JsonValue: - """Exercise either runtime operation with complete authored settings or no config.""" + """Pass an admitted selection directly to either service operation and preserve its response.""" if direction == "inputs": - return service.moderate_inputs(_TENANT_ID, "test-app-id", config, {"q": "a"}, "hello") - return service.moderate_outputs(_TENANT_ID, "test-app-id", config, "hello world") + return service.moderate_inputs(_TENANT_ID, "test-app-id", selection, {"q": "a"}, "hello") + return service.moderate_outputs(_TENANT_ID, "test-app-id", selection, "hello world") + + +def _factory_moderate( + app: Flask, + config: Mapping[str, object] | None, + direction: Literal["inputs", "outputs"], + inputs: dict[str, object] | None = None, +) -> ModerationInputsResult | ModerationOutputsResult: + """Admit raw settings through the real factory and its app-bound service, propagating failures.""" + factory = ModerationFactory("api", "app", _TENANT_ID, dict(config) if config is not None else None) + with app.app_context(): + if direction == "inputs": + return factory.moderation_for_inputs({} if inputs is None else inputs) + return factory.moderation_for_outputs("answer") @pytest.mark.parametrize(("inputs_enabled", "outputs_enabled"), [(True, True), (True, False), (False, True)]) def test_validate_config_success( - service: APIModerationService, + moderation_app: Flask, api_config: APIModerationConfig, lookup_events: list[str], inputs_enabled: bool, @@ -170,31 +197,31 @@ def test_validate_config_success( """Each valid combination permits one scoped read and no outbound work.""" api_config["inputs_config"]["enabled"] = inputs_enabled api_config["outputs_config"]["enabled"] = outputs_enabled - service.validate_config(_TENANT_ID, api_config) + with moderation_app.app_context(): + ModerationFactory.validate_config("api", _TENANT_ID, dict(api_config)) assert lookup_events == ["checkout", "checkin"] @pytest.mark.parametrize("config", [{}, {"inputs_config": [], "outputs_config": []}, {"inputs_config": {}}]) def test_validate_config_rejects_invalid_config_before_lookup( - service: APIModerationService, + moderation_app: Flask, config: dict[str, JsonValue], lookup_events: list[str], lookup_queries: list[str], ) -> None: """Raw malformed forms fail validation before acquiring or querying a connection.""" - with pytest.raises(ValidationError): - service.validate_config(_TENANT_ID, config) + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory.validate_config("api", _TENANT_ID, config) assert lookup_events == [] assert lookup_queries == [] @pytest.mark.parametrize("extension_id", [_MISSING_EXTENSION_ID, _FOREIGN_EXTENSION_ID]) def test_validate_config_extension_not_found( - service: APIModerationService, extension_id: str, api_config: APIModerationConfig, lookup_events: list[str] + service: APIModerationService, extension_id: str, lookup_events: list[str] ) -> None: - api_config["api_based_extension_id"] = extension_id with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): - service.validate_config(_TENANT_ID, api_config) + service.validate_config(_TENANT_ID, EnabledDirection(extension_id)) assert lookup_events == ["checkout", "checkin"] @@ -202,7 +229,6 @@ def test_validate_config_extension_not_found( def test_enabled_moderation_releases_connection_before_external_io( service: APIModerationService, direction: Literal["inputs", "outputs"], - api_config: APIModerationConfig, lookup_events: list[str], outbound: _Outbound, ) -> None: @@ -212,7 +238,7 @@ def test_enabled_moderation_releases_connection_before_external_io( expected = {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"} else: expected = {"app_id": "test-app-id", "text": "hello world"} - assert _moderate(service, api_config, direction) is outbound.response + assert _moderate(service, EnabledDirection(_EXTENSION_ID), direction) is outbound.response assert outbound.params is not None assert outbound.params.model_dump() == expected assert lookup_events == ["checkout", "checkin", "decrypt", "request"] @@ -224,19 +250,17 @@ def test_enabled_moderation_extension_not_found( service: APIModerationService, direction: Literal["inputs", "outputs"], extension_id: str, - api_config: APIModerationConfig, lookup_events: list[str], ) -> None: """Missing and foreign valid string IDs retain the scoped not-found failure.""" - api_config["api_based_extension_id"] = extension_id with pytest.raises(ValueError, match=_EXTENSION_NOT_FOUND): - _moderate(service, api_config, direction) + _moderate(service, EnabledDirection(extension_id), direction) assert lookup_events == ["checkout", "checkin"] @pytest.mark.parametrize("direction", ["inputs", "outputs"]) def test_disabled_moderation_skips_lookup( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], api_config: APIModerationConfig, lookup_events: list[str], @@ -246,22 +270,26 @@ def test_disabled_moderation_skips_lookup( api_config["inputs_config"] = {"enabled": False} else: api_config["outputs_config"] = {"enabled": False} - assert _moderate(service, api_config, direction) == { - "flagged": False, - "action": "direct_output", - "preset_response": "", - } + result = _factory_moderate(moderation_app, api_config, direction) + if direction == "inputs": + assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) + else: + assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) assert lookup_events == [] @pytest.mark.parametrize("direction", ["inputs", "outputs"]) def test_moderation_without_config_skips_lookup( - service: APIModerationService, direction: Literal["inputs", "outputs"], lookup_events: list[str] + moderation_app: Flask, + direction: Literal["inputs", "outputs"], + lookup_events: list[str], + lookup_queries: list[str], ) -> None: """Absent runtime config retains its explicit error before persistence access.""" with pytest.raises(ValueError, match=r"^The config is not set\.$"): - _moderate(service, None, direction) + _factory_moderate(moderation_app, None, direction) assert lookup_events == [] + assert lookup_queries == [] def test_parse_direction_no_config(lookup_events: list[str]) -> None: @@ -271,7 +299,7 @@ def test_parse_direction_no_config(lookup_events: list[str]) -> None: def test_lookup_failure_releases_connection( - service: APIModerationService, api_config: APIModerationConfig, lookup_events: list[str], sqlite_engine: Engine + service: APIModerationService, lookup_events: list[str], sqlite_engine: Engine ) -> None: failure = RuntimeError("lookup failed") @@ -281,7 +309,7 @@ def fail_query(*_args: object) -> None: event.listen(sqlite_engine, "before_cursor_execute", fail_query) try: with pytest.raises(RuntimeError) as exc_info: - service.moderate_outputs(_TENANT_ID, "test-app-id", api_config, "test") + service.moderate_outputs(_TENANT_ID, "test-app-id", EnabledDirection(_EXTENSION_ID), "test") finally: event.remove(sqlite_engine, "before_cursor_execute", fail_query) assert exc_info.value is failure @@ -292,7 +320,6 @@ def fail_query(*_args: object) -> None: @pytest.mark.parametrize("stage", ["decrypt", "request"]) def test_external_failure_preserves_identity_after_checkin( service: APIModerationService, - api_config: APIModerationConfig, outbound: _Outbound, lookup_events: list[str], direction: Literal["inputs", "outputs"], @@ -302,7 +329,7 @@ def test_external_failure_preserves_identity_after_checkin( failure = RuntimeError(f"{stage} failed") outbound.failure = (stage, failure) with pytest.raises(RuntimeError) as exc_info: - _moderate(service, api_config, direction) + _moderate(service, EnabledDirection(_EXTENSION_ID), direction) assert exc_info.value is failure expected = ["checkout", "checkin", "decrypt"] if stage == "request": @@ -314,7 +341,7 @@ def test_external_failure_preserves_identity_after_checkin( @pytest.mark.parametrize("validation", ["runtime", "form"]) @pytest.mark.parametrize("value", ["yes", "false", "", 0, 1, [], [False], {}, {"enabled": True}, None]) def test_non_boolean_flags_are_rejected_before_lookup( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], validation: Literal["runtime", "form"], value: JsonValue, @@ -329,14 +356,11 @@ def test_non_boolean_flags_are_rejected_before_lookup( } raw[f"{direction}_config"] = {"enabled": value} if validation == "form": - with pytest.raises(ValidationError): - service.validate_config(_TENANT_ID, raw) - elif direction == "inputs": - with pytest.raises(ValidationError): - service.moderate_inputs(_TENANT_ID, "app", raw, {}) + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory.validate_config("api", _TENANT_ID, raw) else: with pytest.raises(ValidationError): - service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + _factory_moderate(moderation_app, raw, direction) assert lookup_events == [] assert lookup_queries == [] @@ -345,7 +369,7 @@ def test_non_boolean_flags_are_rejected_before_lookup( @pytest.mark.parametrize("validation", ["runtime", "form"]) @pytest.mark.parametrize("selected", [None, [], "invalid", 1, {}]) def test_malformed_direction_is_rejected_before_lookup( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], validation: Literal["runtime", "form"], selected: JsonValue, @@ -360,14 +384,11 @@ def test_malformed_direction_is_rejected_before_lookup( } raw[f"{direction}_config"] = selected if validation == "form": - with pytest.raises(ValidationError): - service.validate_config(_TENANT_ID, raw) - elif direction == "inputs": - with pytest.raises(ValidationError): - service.moderate_inputs(_TENANT_ID, "app", raw, {}) + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory.validate_config("api", _TENANT_ID, raw) else: with pytest.raises(ValidationError): - service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + _factory_moderate(moderation_app, raw, direction) assert lookup_events == [] assert lookup_queries == [] @@ -375,7 +396,7 @@ def test_malformed_direction_is_rejected_before_lookup( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) @pytest.mark.parametrize("validation", ["runtime", "form"]) def test_missing_direction_is_rejected_before_lookup( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], validation: Literal["runtime", "form"], lookup_events: list[str], @@ -385,14 +406,11 @@ def test_missing_direction_is_rejected_before_lookup( opposite = "outputs_config" if direction == "inputs" else "inputs_config" raw: dict[str, JsonValue] = {opposite: {"enabled": True}, "api_based_extension_id": _EXTENSION_ID} if validation == "form": - with pytest.raises(ValidationError): - service.validate_config(_TENANT_ID, raw) - elif direction == "inputs": - with pytest.raises(ValidationError): - service.moderate_inputs(_TENANT_ID, "app", raw, {}) + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory.validate_config("api", _TENANT_ID, raw) else: with pytest.raises(ValidationError): - service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + _factory_moderate(moderation_app, raw, direction) assert lookup_events == [] assert lookup_queries == [] @@ -400,7 +418,7 @@ def test_missing_direction_is_rejected_before_lookup( @pytest.mark.parametrize("operation", ["inputs", "outputs", "form"]) @pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) def test_invalid_extension_id_is_rejected_before_lookup( - service: APIModerationService, + moderation_app: Flask, operation: Literal["inputs", "outputs", "form"], extension_config: dict[str, JsonValue], lookup_events: list[str], @@ -413,21 +431,18 @@ def test_invalid_extension_id_is_rejected_before_lookup( **extension_config, } if operation == "form": - with pytest.raises(ValidationError): - service.validate_config(_TENANT_ID, raw) - elif operation == "inputs": - with pytest.raises(ValidationError): - service.moderate_inputs(_TENANT_ID, "app", raw, {}) + with moderation_app.app_context(), pytest.raises(ValidationError): + ModerationFactory.validate_config("api", _TENANT_ID, raw) else: with pytest.raises(ValidationError): - service.moderate_outputs(_TENANT_ID, "app", raw, "answer") + _factory_moderate(moderation_app, raw, operation) assert lookup_events == [] assert lookup_queries == [] @pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) def test_both_disabled_form_precedes_extension_id_validation( - service: APIModerationService, + moderation_app: Flask, extension_config: dict[str, JsonValue], lookup_events: list[str], lookup_queries: list[str], @@ -439,19 +454,19 @@ def test_both_disabled_form_precedes_extension_id_validation( **extension_config, } message = "At least one of inputs_config or outputs_config must be enabled" - with pytest.raises(ValueError, match=f"^{re.escape(message)}$"): - service.validate_config(_TENANT_ID, raw) + with moderation_app.app_context(), pytest.raises(ValueError, match=f"^{re.escape(message)}$"): + ModerationFactory.validate_config("api", _TENANT_ID, raw) assert lookup_events == [] assert lookup_queries == [] def test_form_parses_inputs_direction_before_outputs_direction( - service: APIModerationService, lookup_events: list[str], lookup_queries: list[str] + moderation_app: Flask, lookup_events: list[str], lookup_queries: list[str] ) -> None: """The input direction's missing flag wins over malformed output settings.""" raw: dict[str, JsonValue] = {"inputs_config": {}, "outputs_config": None} - with pytest.raises(ValidationError) as raised: - service.validate_config(_TENANT_ID, raw) + with moderation_app.app_context(), pytest.raises(ValidationError) as raised: + ModerationFactory.validate_config("api", _TENANT_ID, raw) assert [(error["loc"], error["type"]) for error in raised.value.errors()] == [(("enabled",), "missing")] assert lookup_events == [] assert lookup_queries == [] @@ -460,24 +475,21 @@ def test_form_parses_inputs_direction_before_outputs_direction( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) @pytest.mark.parametrize("extension_config", _INVALID_EXTENSION_CONFIGS) def test_disabled_direction_ignores_invalid_id_opposite_settings_and_payload( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], extension_config: dict[str, JsonValue], lookup_events: list[str], lookup_queries: list[str], ) -> None: """A false selected flag skips invalid ID, opposite settings and input values.""" - selected: Literal["inputs_config", "outputs_config"] = ( - "inputs_config" if direction == "inputs" else "outputs_config" - ) + selected = "inputs_config" if direction == "inputs" else "outputs_config" opposite = "outputs_config" if direction == "inputs" else "inputs_config" raw: dict[str, JsonValue] = {selected: {"enabled": False}, opposite: None, **extension_config} - assert parse_direction(raw, selected) == DisabledDirection() + result = _factory_moderate(moderation_app, raw, direction, {"unsupported": object()}) if direction == "inputs": - result = service.moderate_inputs(_TENANT_ID, "app", raw, {"unsupported": object()}) + assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) else: - result = service.moderate_outputs(_TENANT_ID, "app", raw, "answer") - assert result == {"flagged": False, "action": "direct_output", "preset_response": ""} + assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) assert lookup_events == [] assert lookup_queries == [] @@ -485,11 +497,10 @@ def test_disabled_direction_ignores_invalid_id_opposite_settings_and_payload( @pytest.mark.parametrize("direction", ["inputs", "outputs"]) @pytest.mark.parametrize("opposite_value", [None, [], "invalid", 1, {}, {"enabled": "yes"}]) def test_enabled_direction_ignores_malformed_opposite_settings( - service: APIModerationService, + moderation_app: Flask, direction: Literal["inputs", "outputs"], opposite_value: JsonValue, lookup_events: list[str], - outbound: _Outbound, ) -> None: """An enabled runtime selection reads only its own direction settings.""" selected = "inputs_config" if direction == "inputs" else "outputs_config" @@ -499,11 +510,11 @@ def test_enabled_direction_ignores_malformed_opposite_settings( opposite: opposite_value, "api_based_extension_id": _EXTENSION_ID, } + result = _factory_moderate(moderation_app, raw, direction) if direction == "inputs": - result = service.moderate_inputs(_TENANT_ID, "app", raw, {}) + assert result == ModerationInputsResult(action=ModerationAction.DIRECT_OUTPUT) else: - result = service.moderate_outputs(_TENANT_ID, "app", raw, "answer") - assert result is outbound.response + assert result == ModerationOutputsResult(action=ModerationAction.DIRECT_OUTPUT) assert lookup_events == ["checkout", "checkin", "decrypt", "request"] @@ -521,20 +532,33 @@ def test_direction_selection_preserves_string_ids_and_ignores_unknown_keys(exten @pytest.mark.parametrize("inputs", [{"invalid": object()}, {"invalid": [object()]}, {"invalid": {"nested": object()}}]) def test_enabled_input_payload_rejects_unsupported_values_before_lookup( service: APIModerationService, - api_config: APIModerationConfig, inputs: dict[str, object], lookup_events: list[str], lookup_queries: list[str], ) -> None: """Arbitrary objects, including nested ones, fail admission before any I/O.""" with pytest.raises(ValidationError): - service.moderate_inputs(_TENANT_ID, "app", api_config, inputs) + service.moderate_inputs(_TENANT_ID, "app", EnabledDirection(_EXTENSION_ID), inputs) assert lookup_events == [] assert lookup_queries == [] -def test_input_domain_survives_sqlite_and_gateway_serialization( +@pytest.mark.parametrize("inputs", [{"invalid": object()}, {"invalid": [object()]}, {"invalid": {"nested": object()}}]) +def test_factory_enabled_input_payload_rejects_unsupported_values_before_lookup( + moderation_app: Flask, api_config: APIModerationConfig, + inputs: dict[str, object], + lookup_events: list[str], + lookup_queries: list[str], +) -> None: + """Raw factory admission keeps enabled payload failures ahead of persistence and outbound work.""" + with pytest.raises(ValidationError): + _factory_moderate(moderation_app, api_config, "inputs", inputs) + assert lookup_events == [] + assert lookup_queries == [] + + +def test_input_domain_survives_sqlite_and_gateway_serialization( sqlite_session_factory: sessionmaker[Session], outbound: _Outbound, lookup_events: list[str], @@ -602,7 +626,9 @@ def request_inputs(endpoint: str, key: str, params: ModerationInputParams) -> Js request_inputs=request_inputs, request_outputs=gateway.outputs, ) - assert service.moderate_inputs(_TENANT_ID, "test-app-id", api_config, values, "hello") is response + assert ( + service.moderate_inputs(_TENANT_ID, "test-app-id", EnabledDirection(_EXTENSION_ID), values, "hello") is response + ) assert len(admitted) == 1 params = admitted[0] assert params.inputs == values @@ -611,24 +637,24 @@ def request_inputs(endpoint: str, key: str, params: ModerationInputParams) -> Js assert isinstance(files, list) assert len(files) == 1 assert files[0] is attachment - assert isinstance(params.inputs["file_json"], dict) assert params.inputs["file_json"] == file_shaped_json - mixed = params.inputs["mixed"] - assert isinstance(mixed, list) - assert type(mixed[0]) is int - assert type(mixed[1]) is bool expected = { "app_id": "test-app-id", "inputs": {**values, "file": attachment.model_dump(), "files": [attachment.model_dump()]}, "query": "hello", } - assert calls == [(_ENDPOINT, "decrypted-key", APIBasedExtensionPoint.APP_MODERATION_INPUT, expected)] + assert len(calls) == 1 + endpoint, key, point, payload = calls[0] + assert (endpoint, key, point) == (_ENDPOINT, "decrypted-key", APIBasedExtensionPoint.APP_MODERATION_INPUT) + assert json.dumps(payload, sort_keys=True, ensure_ascii=False) == json.dumps( + expected, sort_keys=True, ensure_ascii=False + ) assert lookup_events == ["checkout", "checkin", "decrypt", "request"] assert lookup_queries == ["query"] def test_service_uses_explicit_database_instead_of_global( - sqlite_session_factory: sessionmaker[Session], api_config: APIModerationConfig + sqlite_session_factory: sessionmaker[Session], ) -> None: """The autouse global DB is empty; only the independently supplied DB owns this ID.""" assert ( @@ -653,7 +679,7 @@ def test_service_uses_explicit_database_instead_of_global( request_inputs=outbound.inputs, request_outputs=outbound.outputs, ) - explicit_service.validate_config(_TENANT_ID, api_config) + explicit_service.validate_config(_TENANT_ID, EnabledDirection(_EXTENSION_ID)) assert ( APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension( _TENANT_ID, _EXTENSION_ID From 80d66a117379d66805afd9a63b14ccbf414fbbf6 Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Wed, 18 Nov 2026 13:23:53 +0800 Subject: [PATCH 11/12] test(api): tighten moderation review coverage --- .../unit_tests/services/test_api_based_extension_adapters.py | 1 - api/tests/unit_tests/services/test_api_moderation_service.py | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/api/tests/unit_tests/services/test_api_based_extension_adapters.py b/api/tests/unit_tests/services/test_api_based_extension_adapters.py index 8e1c2dcfe90224..795978e18b7a5c 100644 --- a/api/tests/unit_tests/services/test_api_based_extension_adapters.py +++ b/api/tests/unit_tests/services/test_api_based_extension_adapters.py @@ -147,7 +147,6 @@ def request(endpoint: str, key: str, point: APIBasedExtensionPoint, payload: dic assert isinstance(files, list) assert len(files) == 1 assert files[0] is attachment - assert isinstance(params.inputs["file_json"], dict) assert params.inputs["file_json"] == file_shaped_json expected = { "app_id": "", diff --git a/api/tests/unit_tests/services/test_api_moderation_service.py b/api/tests/unit_tests/services/test_api_moderation_service.py index d9c05edb1dccbb..d83fe2b4c297d9 100644 --- a/api/tests/unit_tests/services/test_api_moderation_service.py +++ b/api/tests/unit_tests/services/test_api_moderation_service.py @@ -14,7 +14,6 @@ from domain.moderation.api_config import APIModerationConfig, DisabledDirection, EnabledDirection, parse_direction from graphon.file import File, FileTransferMethod, FileType from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint -from models.base import TypeBase from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_based_extension_adapters import APIModerationGateway from services.api_moderation_service import ( @@ -663,7 +662,7 @@ def test_service_uses_explicit_database_instead_of_global( ) engine = create_engine("sqlite://") try: - TypeBase.metadata.create_all(engine) + APIBasedExtension.metadata.tables[APIBasedExtension.__tablename__].create(engine) explicit_factory = sessionmaker(bind=engine) repository = APIBasedExtensionRepository(session_factory=explicit_factory) target = APIBasedExtension( From d617b0b83726db4bcb4f7b507bff604fe303ab7f Mon Sep 17 00:00:00 2001 From: Eddy Zhang Date: Sat, 28 Nov 2026 21:46:20 +0800 Subject: [PATCH 12/12] refactor(api): carry typed moderation payloads to HTTP adapters --- api/core/moderation/api/api.py | 46 ++------ api/core/moderation/base.py | 5 +- api/domain/moderation/__init__.py | 0 api/domain/moderation/api_parameters.py | 14 +++ api/services/api_moderation_adapters.py | 13 ++- api/services/api_moderation_service.py | 9 +- .../core/moderation/api/test_api.py | 107 +++++++----------- .../services/test_api_moderation_service.py | 98 ++++++++++++---- 8 files changed, 155 insertions(+), 137 deletions(-) create mode 100644 api/domain/moderation/__init__.py create mode 100644 api/domain/moderation/api_parameters.py diff --git a/api/core/moderation/api/api.py b/api/core/moderation/api/api.py index d5427389eb8bb3..3a84f7fec00c22 100644 --- a/api/core/moderation/api/api.py +++ b/api/core/moderation/api/api.py @@ -1,8 +1,5 @@ from typing import Any, override -from pydantic import BaseModel, Field, JsonValue - -from core.extension.api_based_extension_requestor import APIBasedExtensionPoint from core.moderation.base import ( ApiModerationRuntime, Moderation, @@ -11,17 +8,7 @@ ModerationOutputsResult, ) from core.moderation.factory import get_api_moderation - - -class ModerationInputParams(BaseModel): - app_id: str = "" - inputs: dict[str, Any] = Field(default_factory=dict) - query: str = "" - - -class ModerationOutputParams(BaseModel): - app_id: str = "" - text: str +from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams class ApiModeration(Moderation): @@ -56,10 +43,10 @@ def moderation_for_inputs(self, inputs: dict[str, Any], query: str = "") -> Mode if self.config["inputs_config"]["enabled"]: params = ModerationInputParams(app_id=self.app_id, inputs=inputs, query=query) - result = self._get_config_by_requestor( - APIBasedExtensionPoint.APP_MODERATION_INPUT, - params.model_dump(), + result = self._get_runtime().request_inputs( + self.tenant_id, self.config.get("api_based_extension_id", ""), + params, ) return ModerationInputsResult.model_validate(result) @@ -77,10 +64,10 @@ def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: if self.config["outputs_config"]["enabled"]: params = ModerationOutputParams(app_id=self.app_id, text=text) - result = self._get_config_by_requestor( - APIBasedExtensionPoint.APP_MODERATION_OUTPUT, - params.model_dump(), + result = self._get_runtime().request_outputs( + self.tenant_id, self.config.get("api_based_extension_id", ""), + params, ) return ModerationOutputsResult.model_validate(result) @@ -88,22 +75,11 @@ def moderation_for_outputs(self, text: str) -> ModerationOutputsResult: flagged=flagged, action=ModerationAction.DIRECT_OUTPUT, preset_response=preset_response ) - def _get_config_by_requestor( - self, extension_point: APIBasedExtensionPoint, params: dict[str, Any], extension_id: str - ) -> JsonValue: - """Use the first enabled request's app runtime, preserving it across contexts. + def _get_runtime(self) -> ApiModerationRuntime: + """Bind on the first enabled request and preserve that runtime across contexts. - Parameters and the explicit extension ID come from the legacy entrypoint. - Missing configuration or runtime bindings fail before external work. + A missing or invalid application binding raises before external work. """ - if self.config is None: - raise ValueError("The config is not set.") if self._runtime is None: self._runtime = get_api_moderation() - runtime = self._runtime - request = ( - runtime.request_inputs - if extension_point == APIBasedExtensionPoint.APP_MODERATION_INPUT - else runtime.request_outputs - ) - return request(self.tenant_id, extension_id, params) + return self._runtime diff --git a/api/core/moderation/base.py b/api/core/moderation/base.py index 523010894f8efa..96ff9f8104ffda 100644 --- a/api/core/moderation/base.py +++ b/api/core/moderation/base.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from core.app.app_config.entities import AppConfig + from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams @runtime_checkable @@ -23,9 +24,9 @@ class ApiModerationRuntime(Protocol): def validate_extension(self, tenant_id: str, extension_id: str) -> None: ... - def request_inputs(self, tenant_id: str, extension_id: str, params: dict[str, object]) -> JsonValue: ... + def request_inputs(self, tenant_id: str, extension_id: str, params: ModerationInputParams) -> JsonValue: ... - def request_outputs(self, tenant_id: str, extension_id: str, params: dict[str, object]) -> JsonValue: ... + def request_outputs(self, tenant_id: str, extension_id: str, params: ModerationOutputParams) -> JsonValue: ... @runtime_checkable diff --git a/api/domain/moderation/__init__.py b/api/domain/moderation/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/api/domain/moderation/api_parameters.py b/api/domain/moderation/api_parameters.py new file mode 100644 index 00000000000000..54297828da7e40 --- /dev/null +++ b/api/domain/moderation/api_parameters.py @@ -0,0 +1,14 @@ +"""API moderation retains legacy coercion and unconstrained extension input values.""" + +from pydantic import BaseModel, Field + + +class ModerationInputParams(BaseModel): + app_id: str = "" + inputs: dict[str, object] = Field(default_factory=dict) + query: str = "" + + +class ModerationOutputParams(BaseModel): + app_id: str = "" + text: str diff --git a/api/services/api_moderation_adapters.py b/api/services/api_moderation_adapters.py index be7ffbdef4cb6d..4d464d5a903bb2 100644 --- a/api/services/api_moderation_adapters.py +++ b/api/services/api_moderation_adapters.py @@ -3,17 +3,18 @@ from pydantic import JsonValue from core.extension.api_based_extension_requestor import APIBasedExtensionPoint, APIBasedExtensionRequestor +from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams -def request_inputs(api_endpoint: str, api_key: str, params: dict[str, object]) -> JsonValue: - """Send input parameters unchanged and return JSON, propagating request failures.""" +def request_inputs(api_endpoint: str, api_key: str, params: ModerationInputParams) -> JsonValue: + """Serialize input parameters and return JSON, propagating request failures.""" return APIBasedExtensionRequestor(api_endpoint, api_key).request( - APIBasedExtensionPoint.APP_MODERATION_INPUT, params + APIBasedExtensionPoint.APP_MODERATION_INPUT, params.model_dump() ) -def request_outputs(api_endpoint: str, api_key: str, params: dict[str, object]) -> JsonValue: - """Send output parameters unchanged and return JSON, propagating request failures.""" +def request_outputs(api_endpoint: str, api_key: str, params: ModerationOutputParams) -> JsonValue: + """Serialize output parameters and return JSON, propagating request failures.""" return APIBasedExtensionRequestor(api_endpoint, api_key).request( - APIBasedExtensionPoint.APP_MODERATION_OUTPUT, params + APIBasedExtensionPoint.APP_MODERATION_OUTPUT, params.model_dump() ) diff --git a/api/services/api_moderation_service.py b/api/services/api_moderation_service.py index bc54a06b019e1d..f9219c3ce693f6 100644 --- a/api/services/api_moderation_service.py +++ b/api/services/api_moderation_service.py @@ -8,6 +8,7 @@ from pydantic import JsonValue +from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams from services.api_based_extension_application_service import APIBasedExtensionRecord @@ -19,8 +20,8 @@ def __init__( *, find_extension: Callable[[str, str], APIBasedExtensionRecord | None], decrypt_key: Callable[[str, str], str], - request_inputs: Callable[[str, str, dict[str, object]], JsonValue], - request_outputs: Callable[[str, str, dict[str, object]], JsonValue], + request_inputs: Callable[[str, str, ModerationInputParams], JsonValue], + request_outputs: Callable[[str, str, ModerationOutputParams], JsonValue], ) -> None: """Bind required capabilities without looking up or decrypting credentials.""" self._find_extension = find_extension @@ -36,7 +37,7 @@ def validate_extension(self, tenant_id: str, extension_id: str) -> None: """ self._require_extension(tenant_id, extension_id) - def request_inputs(self, tenant_id: str, extension_id: str, params: dict[str, object]) -> JsonValue: + def request_inputs(self, tenant_id: str, extension_id: str, params: ModerationInputParams) -> JsonValue: """Send admitted input parameters after the scoped lookup has finished. Return the wire response for the caller's existing result validation. @@ -46,7 +47,7 @@ def request_inputs(self, tenant_id: str, extension_id: str, params: dict[str, ob key = self._decrypt_key(tenant_id, extension.api_key) return self._request_inputs(extension.api_endpoint, key, params) - def request_outputs(self, tenant_id: str, extension_id: str, params: dict[str, object]) -> JsonValue: + def request_outputs(self, tenant_id: str, extension_id: str, params: ModerationOutputParams) -> JsonValue: """Send admitted output parameters after the scoped lookup has finished. Return the wire response for the caller's existing result validation. diff --git a/api/tests/unit_tests/core/moderation/api/test_api.py b/api/tests/unit_tests/core/moderation/api/test_api.py index 6ce11b94b48929..65a1ae05b308ed 100644 --- a/api/tests/unit_tests/core/moderation/api/test_api.py +++ b/api/tests/unit_tests/core/moderation/api/test_api.py @@ -1,15 +1,14 @@ from collections.abc import Iterator from dataclasses import dataclass, field -from unittest.mock import MagicMock, patch import pytest from flask import Flask -from pydantic import JsonValue, ValidationError +from pydantic import JsonValue from sqlalchemy.orm import Session, sessionmaker -from core.extension.api_based_extension_requestor import APIBasedExtensionPoint -from core.moderation.api.api import ApiModeration, ModerationInputParams, ModerationOutputParams +from core.moderation.api.api import ApiModeration from core.moderation.base import ModerationAction, ModerationInputsResult, ModerationOutputsResult +from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams from models.api_based_extension import APIBasedExtension from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_moderation_service import APIModerationService @@ -17,16 +16,22 @@ @dataclass class _Outbound: - calls: list[tuple[str, str, dict[str, object]]] = field(default_factory=list) + input_calls: list[tuple[str, str, ModerationInputParams]] = field(default_factory=list) + output_calls: list[tuple[str, str, ModerationOutputParams]] = field(default_factory=list) decrypt_calls: list[tuple[str, str]] = field(default_factory=list) + response: JsonValue = field(default_factory=lambda: {"flagged": True, "action": "direct_output"}) def decrypt(self, tenant_id: str, ciphertext: str) -> str: self.decrypt_calls.append((tenant_id, ciphertext)) return "decrypted-key" - def request(self, endpoint: str, key: str, params: dict[str, object]) -> JsonValue: - self.calls.append((endpoint, key, params)) - return {"flagged": True} + def inputs(self, endpoint: str, key: str, params: ModerationInputParams) -> JsonValue: + self.input_calls.append((endpoint, key, params)) + return self.response + + def outputs(self, endpoint: str, key: str, params: ModerationOutputParams) -> JsonValue: + self.output_calls.append((endpoint, key, params)) + return self.response class TestApiModeration: @@ -46,8 +51,8 @@ def bound_runtime(self, sqlite_session_factory: sessionmaker[Session]) -> Iterat app.extensions["api_moderation"] = APIModerationService( find_extension=APIBasedExtensionRepository(session_factory=sqlite_session_factory).find_extension, decrypt_key=outbound.decrypt, - request_inputs=outbound.request, - request_outputs=outbound.request, + request_inputs=outbound.inputs, + request_outputs=outbound.outputs, ) with app.app_context(): yield outbound @@ -68,30 +73,11 @@ def api_config(self) -> dict[str, object]: def api_moderation(self, api_config: dict[str, object]) -> ApiModeration: return ApiModeration(app_id="test-app-id", tenant_id="test-tenant-id", config=api_config) - def test_moderation_input_params(self) -> None: - params = ModerationInputParams(app_id="app-1", inputs={"key": "val"}, query="test query") - assert params.app_id == "app-1" - assert params.inputs == {"key": "val"} - assert params.query == "test query" - - # Test defaults - params_default = ModerationInputParams() - assert params_default.app_id == "" - assert params_default.inputs == {} - assert params_default.query == "" - - def test_moderation_output_params(self) -> None: - params = ModerationOutputParams(app_id="app-1", text="test text") - assert params.app_id == "app-1" - assert params.text == "test text" - - with pytest.raises(ValidationError): - ModerationOutputParams() # pyrefly: ignore[missing-argument] - def test_validate_config_success(self, bound_runtime: _Outbound, api_config: dict[str, object]) -> None: ApiModeration.validate_config("test-tenant-id", api_config) assert bound_runtime.decrypt_calls == [] - assert bound_runtime.calls == [] + assert bound_runtime.input_calls == [] + assert bound_runtime.output_calls == [] def test_validate_config_missing_extension_id(self) -> None: config = { @@ -106,9 +92,8 @@ def test_validate_config_extension_not_found(self, api_config: dict[str, object] with pytest.raises(ValueError, match="API-based Extension not found"): ApiModeration.validate_config("test-tenant-id", api_config) - @patch("core.moderation.api.api.ApiModeration._get_config_by_requestor") - def test_moderation_for_inputs_enabled(self, mock_get_config: MagicMock, api_moderation: ApiModeration) -> None: - mock_get_config.return_value = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} + def test_moderation_for_inputs_enabled(self, bound_runtime: _Outbound, api_moderation: ApiModeration) -> None: + bound_runtime.response = {"flagged": True, "action": "direct_output", "preset_response": "Blocked by API"} result = api_moderation.moderation_for_inputs(inputs={"q": "a"}, query="hello") @@ -117,11 +102,15 @@ def test_moderation_for_inputs_enabled(self, mock_get_config: MagicMock, api_mod assert result.action == ModerationAction.DIRECT_OUTPUT assert result.preset_response == "Blocked by API" - mock_get_config.assert_called_once_with( - APIBasedExtensionPoint.APP_MODERATION_INPUT, - {"app_id": "test-app-id", "inputs": {"q": "a"}, "query": "hello"}, - "test-extension-id", - ) + assert bound_runtime.decrypt_calls == [("test-tenant-id", "encrypted-key")] + assert bound_runtime.input_calls == [ + ( + "http://api.test", + "decrypted-key", + ModerationInputParams(app_id="test-app-id", inputs={"q": "a"}, query="hello"), + ) + ] + assert bound_runtime.output_calls == [] def test_moderation_for_inputs_disabled(self) -> None: config = { @@ -141,20 +130,18 @@ def test_moderation_for_inputs_no_config(self) -> None: with pytest.raises(ValueError, match="The config is not set"): moderation.moderation_for_inputs({}, "") - @patch("core.moderation.api.api.ApiModeration._get_config_by_requestor") - def test_moderation_for_outputs_enabled(self, mock_get_config: MagicMock, api_moderation: ApiModeration) -> None: - mock_get_config.return_value = {"flagged": False, "action": "direct_output", "preset_response": ""} + def test_moderation_for_outputs_enabled(self, bound_runtime: _Outbound, api_moderation: ApiModeration) -> None: + bound_runtime.response = {"flagged": False, "action": "direct_output", "preset_response": ""} result = api_moderation.moderation_for_outputs(text="hello world") assert isinstance(result, ModerationOutputsResult) assert result.flagged is False - mock_get_config.assert_called_once_with( - APIBasedExtensionPoint.APP_MODERATION_OUTPUT, - {"app_id": "test-app-id", "text": "hello world"}, - "test-extension-id", - ) + assert bound_runtime.output_calls == [ + ("http://api.test", "decrypted-key", ModerationOutputParams(app_id="test-app-id", text="hello world")) + ] + assert bound_runtime.input_calls == [] def test_moderation_for_outputs_disabled(self) -> None: config = { @@ -173,25 +160,15 @@ def test_moderation_for_outputs_no_config(self) -> None: with pytest.raises(ValueError, match="The config is not set"): moderation.moderation_for_outputs("test") - def test_get_config_by_requestor_success(self, bound_runtime: _Outbound, api_moderation: ApiModeration) -> None: - params = {"some": "params"} - result = api_moderation._get_config_by_requestor( - APIBasedExtensionPoint.APP_MODERATION_INPUT, params, "test-extension-id" - ) - - assert result == {"flagged": True} - assert bound_runtime.decrypt_calls == [("test-tenant-id", "encrypted-key")] - assert bound_runtime.calls == [("http://api.test", "decrypted-key", params)] - assert bound_runtime.calls[0][2] is params - - def test_get_config_by_requestor_no_config(self) -> None: - moderation = ApiModeration("app-id", "tenant-id", None) - with pytest.raises(ValueError, match="The config is not set"): - moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}, "test-extension-id") - - def test_get_config_by_requestor_extension_not_found(self, api_moderation: ApiModeration) -> None: + def test_moderation_for_inputs_extension_not_found( + self, api_config: dict[str, object], bound_runtime: _Outbound + ) -> None: + api_config["api_based_extension_id"] = "missing" + moderation = ApiModeration("test-app-id", "test-tenant-id", api_config) with pytest.raises(ValueError, match="API-based Extension not found"): - api_moderation._get_config_by_requestor(APIBasedExtensionPoint.APP_MODERATION_INPUT, {}, "missing") + moderation.moderation_for_inputs({}) + assert bound_runtime.decrypt_calls == [] + assert bound_runtime.input_calls == [] def test_get_api_based_extension( self, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session] diff --git a/api/tests/unit_tests/services/test_api_moderation_service.py b/api/tests/unit_tests/services/test_api_moderation_service.py index d2f33fe4a9d95c..0660f839d182f9 100644 --- a/api/tests/unit_tests/services/test_api_moderation_service.py +++ b/api/tests/unit_tests/services/test_api_moderation_service.py @@ -2,6 +2,7 @@ import json from collections.abc import Iterator +from contextlib import nullcontext from dataclasses import dataclass, field import httpx @@ -14,6 +15,8 @@ from core.moderation.api.api import ApiModeration from core.moderation.base import Moderation from core.moderation.factory import ModerationFactory +from domain.moderation.api_parameters import ModerationInputParams, ModerationOutputParams +from graphon.file import File, FileTransferMethod, FileType from models.api_based_extension import APIBasedExtension from repositories.api_based_extension_repository import APIBasedExtensionRepository from services.api_based_extension_adapters import WorkspaceTokenCipher @@ -29,7 +32,8 @@ def _provide_app_context() -> None: @dataclass class Outbound: events: list[str] - calls: list[tuple[str, str, dict[str, object]]] = field(default_factory=list) + input_calls: list[tuple[str, ModerationInputParams]] = field(default_factory=list) + output_calls: list[tuple[str, ModerationOutputParams]] = field(default_factory=list) response: JsonValue = field(default_factory=lambda: {"flagged": False, "action": "direct_output"}) failure: tuple[str, Exception] | None = None @@ -41,20 +45,23 @@ def decrypt(self, tenant_id: str, ciphertext: str) -> str: self._fail("decrypt") return "plaintext-key" - def inputs(self, endpoint: str, key: str, params: dict[str, object]) -> JsonValue: - return self._request("inputs", endpoint, key, params) + def inputs(self, endpoint: str, key: str, params: ModerationInputParams) -> JsonValue: + self._record_request("inputs", endpoint, key) + self.input_calls.append((endpoint, params)) + self._fail("request") + return self.response - def outputs(self, endpoint: str, key: str, params: dict[str, object]) -> JsonValue: - return self._request("outputs", endpoint, key, params) + def outputs(self, endpoint: str, key: str, params: ModerationOutputParams) -> JsonValue: + self._record_request("outputs", endpoint, key) + self.output_calls.append((endpoint, params)) + self._fail("request") + return self.response - def _request(self, direction: str, endpoint: str, key: str, params: dict[str, object]) -> JsonValue: + def _record_request(self, direction: str, endpoint: str, key: str) -> None: assert endpoint == "https://moderation.example" assert key == "plaintext-key" assert self.events[-2:] == ["checkin", "decrypt"] self.events.append(direction) - self.calls.append((direction, endpoint, params)) - self._fail("request") - return self.response def _fail(self, stage: str) -> None: if self.failure is not None and self.failure[0] == stage: @@ -128,7 +135,8 @@ def test_validation_releases_connection_without_decrypting(app: Flask, outbound: with app.app_context(): ApiModeration.validate_config("tenant-a", config()) assert outbound.events == ["checkout", "checkin"] - assert outbound.calls == [] + assert outbound.input_calls == [] + assert outbound.output_calls == [] def test_validation_lookup_failure_checks_in_and_keeps_error_identity( @@ -145,7 +153,8 @@ def fail_lookup(*_args: object) -> None: ApiModeration.validate_config("tenant-a", config()) assert raised.value is failure assert outbound.events == ["checkout", "checkin"] - assert outbound.calls == [] + assert outbound.input_calls == [] + assert outbound.output_calls == [] finally: event.remove(sqlite_engine, "do_execute", fail_lookup) @@ -164,12 +173,16 @@ def test_enabled_entrypoint_checks_in_before_decrypt_and_request( ) assert result.flagged is False assert outbound.events == ["checkout", "checkin", "decrypt", direction] - expected = ( - {"app_id": "app-a", "inputs": {"x": "value"}, "query": "query"} - if direction == "inputs" - else {"app_id": "app-a", "text": "text"} - ) - assert outbound.calls == [(direction, "https://moderation.example", expected)] + if direction == "inputs": + assert outbound.input_calls == [ + ("https://moderation.example", ModerationInputParams(app_id="app-a", inputs={"x": "value"}, query="query")) + ] + assert outbound.output_calls == [] + else: + assert outbound.output_calls == [ + ("https://moderation.example", ModerationOutputParams(app_id="app-a", text="text")) + ] + assert outbound.input_calls == [] @pytest.mark.parametrize("operation", ["validate", "inputs", "outputs"]) @@ -182,7 +195,8 @@ def test_absent_or_foreign_extension_has_no_outbound_work( with app.app_context(), pytest.raises(ValueError, match="API-based Extension not found"): invoke(provider, operation) assert outbound.events == ["checkout", "checkin"] - assert outbound.calls == [] + assert outbound.input_calls == [] + assert outbound.output_calls == [] @pytest.mark.parametrize("direction", ["inputs", "outputs"]) @@ -250,7 +264,8 @@ def test_first_enabled_operation_binds_active_app_then_survives_other_contexts( outbound.events == ["checkout", "checkin", "decrypt", "inputs"] + ["checkout", "checkin", "decrypt", "outputs"] * 2 ) - assert other_outbound.calls == [] + assert other_outbound.input_calls == [] + assert other_outbound.output_calls == [] def test_missing_context_does_not_bind_and_can_retry(app: Flask, outbound: Outbound) -> None: @@ -329,14 +344,47 @@ def client(*, mounts: dict[str, httpx.BaseTransport] | None, timeout: httpx.Time request_outputs=request_outputs, ) provider = ApiModeration("app-a", "tenant-a", config()) - with app.app_context(): - if malformed_response: - with pytest.raises(ValidationError): - invoke(provider, direction) + file = File( + file_id="file-a", + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.test/file.pdf", + filename="file.pdf", + ) + inputs: dict[str, object] = { + "nested": {"values": [None, True, 7, 2.5, "text"]}, + "file_like": { + "id": "file-like", + "type": "document", + "transfer_method": "remote_url", + "remote_url": "https://example.test/unconstrained.pdf", + "extra": {"keep": [None, False]}, + }, + "file": file, + "files": [file], + } + with app.app_context(), pytest.raises(ValidationError) if malformed_response else nullcontext(): + if direction == "inputs": + provider.moderation_for_inputs(inputs) else: - invoke(provider, direction) + provider.moderation_for_outputs("text") + expected_file = { + "dify_model_identity": "__dify__file__", + "id": "file-a", + "type": "document", + "transfer_method": "remote_url", + "remote_url": "https://example.test/file.pdf", + "reference": None, + "filename": "file.pdf", + "extension": None, + "mime_type": None, + "size": -1, + } expected_params: dict[str, object] = ( - {"app_id": "app-a", "inputs": {}, "query": ""} if direction == "inputs" else {"app_id": "app-a", "text": "text"} + {"app_id": "app-a", "inputs": inputs | {"file": expected_file, "files": [expected_file]}, "query": ""} + if direction == "inputs" + else {"app_id": "app-a", "text": "text"} ) point = "app.moderation.input" if direction == "inputs" else "app.moderation.output" assert sent == [{"point": point, "params": expected_params}] + assert inputs["file"] is file