From 80e7b3dbc0a80df2b3dd269b4b1a700477dd2505 Mon Sep 17 00:00:00 2001 From: Tanishq Date: Wed, 28 Oct 2026 21:14:09 +0530 Subject: [PATCH 1/2] fix(trigger): store webhook uploads under the trigger end user Multipart and octet-stream webhook uploads were saved as ToolFiles owned by the account that created the webhook, but the async run executes as the app's trigger end user, and an end user's file access scope only loads the tool files it owns. The worker then failed with "ToolFile not found" and downstream nodes never received the file. Pass the injected end-user provisioner into request extraction and make the trigger end user the owner of uploaded files. Uploads resolve it once per request through the same helper that trigger_workflow_execution uses for the run identity. --- api/controllers/trigger/webhook.py | 6 +- api/services/trigger/webhook_service.py | 69 +++++++++++----- .../controllers/trigger/test_webhook.py | 76 +++++++++++++++++- .../services/trigger/test_webhook_service.py | 79 +++++++++++++------ 4 files changed, 182 insertions(+), 48 deletions(-) diff --git a/api/controllers/trigger/webhook.py b/api/controllers/trigger/webhook.py index b9734cb9f39db7..c0938d53249ce3 100644 --- a/api/controllers/trigger/webhook.py +++ b/api/controllers/trigger/webhook.py @@ -44,7 +44,11 @@ def _prepare_webhook_execution(webhook_id: str, is_debug: bool = False): webhook_data: RawWebhookDataDict try: # Use new unified extraction and validation - webhook_data = WebhookService.extract_and_validate_webhook_data(webhook_trigger, node_config) + webhook_data = WebhookService.extract_and_validate_webhook_data( + webhook_trigger, + node_config, + end_users=application_services().app_scoped_end_users.commands, + ) return webhook_trigger, workflow, node_config, webhook_data, None except ValueError as e: # Provide minimal context for error reporting without risking another parse failure diff --git a/api/services/trigger/webhook_service.py b/api/services/trigger/webhook_service.py index 0c9f6f8473ffac..85ce61bed9d6c8 100644 --- a/api/services/trigger/webhook_service.py +++ b/api/services/trigger/webhook_service.py @@ -182,13 +182,18 @@ def get_webhook_trigger_and_workflow( @classmethod def extract_and_validate_webhook_data( - cls, webhook_trigger: WorkflowWebhookTrigger, node_config: NodeConfigDict + cls, + webhook_trigger: WorkflowWebhookTrigger, + node_config: NodeConfigDict, + *, + end_users: WebhookEndUserProvisioner, ) -> RawWebhookDataDict: """Extract and validate webhook data in a single unified process. Args: webhook_trigger: The webhook trigger object containing metadata node_config: The node configuration containing validation rules + end_users: Provisioner for the trigger end user that owns uploaded files Returns: dict[str, Any]: Processed and validated webhook data with correct types @@ -197,7 +202,7 @@ def extract_and_validate_webhook_data( ValueError: If validation fails (HTTP method mismatch, missing required fields, type errors) """ # Extract raw data first - raw_data = cls.extract_webhook_data(webhook_trigger) + raw_data = cls.extract_webhook_data(webhook_trigger, end_users=end_users) # Validate HTTP metadata (method, content-type) node_data = WebhookData.model_validate(node_config["data"], from_attributes=True) @@ -211,11 +216,14 @@ def extract_and_validate_webhook_data( return processed_data @classmethod - def extract_webhook_data(cls, webhook_trigger: WorkflowWebhookTrigger) -> RawWebhookDataDict: + def extract_webhook_data( + cls, webhook_trigger: WorkflowWebhookTrigger, *, end_users: WebhookEndUserProvisioner + ) -> RawWebhookDataDict: """Extract raw data from incoming webhook request without type conversion. Args: webhook_trigger: The webhook trigger object for file processing context + end_users: Provisioner for the trigger end user that owns uploaded files Returns: dict[str, Any]: Raw webhook data containing: @@ -242,8 +250,8 @@ def extract_webhook_data(cls, webhook_trigger: WorkflowWebhookTrigger) -> RawWeb extractors: dict[str, Callable[[], tuple[dict[str, Any], dict[str, Any]]]] = { "application/json": cls._extract_json_body, "application/x-www-form-urlencoded": cls._extract_form_body, - "multipart/form-data": lambda: cls._extract_multipart_body(webhook_trigger), - "application/octet-stream": lambda: cls._extract_octet_stream_body(webhook_trigger), + "multipart/form-data": lambda: cls._extract_multipart_body(webhook_trigger, end_users), + "application/octet-stream": lambda: cls._extract_octet_stream_body(webhook_trigger, end_users), "text/plain": cls._extract_text_body, } @@ -332,11 +340,14 @@ def _extract_form_body(cls) -> tuple[dict[str, Any], dict[str, Any]]: return dict(request.form), {} @classmethod - def _extract_multipart_body(cls, webhook_trigger: WorkflowWebhookTrigger) -> tuple[dict[str, Any], dict[str, Any]]: + def _extract_multipart_body( + cls, webhook_trigger: WorkflowWebhookTrigger, end_users: WebhookEndUserProvisioner + ) -> tuple[dict[str, Any], dict[str, Any]]: """Extract multipart/form-data body and files from request. Args: webhook_trigger: Webhook trigger for file processing context + end_users: Provisioner for the trigger end user that owns uploaded files Returns: tuple: (body_data, files_data) where: @@ -344,17 +355,18 @@ def _extract_multipart_body(cls, webhook_trigger: WorkflowWebhookTrigger) -> tup - files_data: Processed file objects indexed by field name """ body = dict(request.form) - files = cls._process_file_uploads(request.files, webhook_trigger) if request.files else {} + files = cls._process_file_uploads(request.files, webhook_trigger, end_users) if request.files else {} return body, files @classmethod def _extract_octet_stream_body( - cls, webhook_trigger: WorkflowWebhookTrigger + cls, webhook_trigger: WorkflowWebhookTrigger, end_users: WebhookEndUserProvisioner ) -> tuple[dict[str, Any], dict[str, Any]]: """Extract binary data as file from request. Args: webhook_trigger: Webhook trigger for file processing context + end_users: Provisioner for the trigger end user that owns the uploaded file Returns: tuple: (body_data, files_data) where: @@ -365,7 +377,8 @@ def _extract_octet_stream_body( file_content = request.get_data() if file_content: mimetype = cls._detect_binary_mimetype(file_content) - file_obj = cls._create_file_from_binary(file_content, mimetype, webhook_trigger) + end_user = cls._resolve_trigger_end_user(webhook_trigger, end_users) + file_obj = cls._create_file_from_binary(file_content, mimetype, webhook_trigger, end_user) return {"raw": file_obj.to_dict()}, {} else: return {"raw": None}, {} @@ -401,27 +414,44 @@ def _detect_binary_mimetype(file_content: bytes) -> str: logger.debug("python-magic detection failed for octet-stream payload") return "application/octet-stream" + @staticmethod + def _resolve_trigger_end_user( + webhook_trigger: WorkflowWebhookTrigger, end_users: WebhookEndUserProvisioner + ) -> EndUser: + """Return the app's trigger end user, the identity that webhook workflow runs execute as.""" + return end_users.get_or_create_end_user_by_type( + type=EndUserType.TRIGGER, + tenant_id=webhook_trigger.tenant_id, + app_id=webhook_trigger.app_id, + user_id=None, + ) + @classmethod def _process_file_uploads( - cls, files: Mapping[str, FileStorage], webhook_trigger: WorkflowWebhookTrigger + cls, + files: Mapping[str, FileStorage], + webhook_trigger: WorkflowWebhookTrigger, + end_users: WebhookEndUserProvisioner, ) -> dict[str, Any]: """Process file uploads using ToolFileManager. Args: files: Flask request files object containing uploaded files - webhook_trigger: Webhook trigger for tenant and user context + webhook_trigger: Webhook trigger for tenant and app context + end_users: Provisioner for the trigger end user that owns uploaded files Returns: dict[str, Any]: Processed file objects indexed by field name """ processed_files = {} + end_user = cls._resolve_trigger_end_user(webhook_trigger, end_users) for name, file in files.items(): if file and file.filename: try: file_content = file.stream.read() mimetype = file.content_type or mimetypes.guess_type(file.filename)[0] or "application/octet-stream" - file_obj = cls._create_file_from_binary(file_content, mimetype, webhook_trigger) + file_obj = cls._create_file_from_binary(file_content, mimetype, webhook_trigger, end_user) processed_files[name] = file_obj.to_dict() except Exception: logger.exception("Failed to process file upload '%s'", name) @@ -431,14 +461,16 @@ def _process_file_uploads( @classmethod def _create_file_from_binary( - cls, file_content: bytes, mimetype: str, webhook_trigger: WorkflowWebhookTrigger + cls, file_content: bytes, mimetype: str, webhook_trigger: WorkflowWebhookTrigger, end_user: EndUser ) -> Any: """Create a file object from binary content using ToolFileManager. Args: file_content: The binary content of the file mimetype: The MIME type of the file - webhook_trigger: Webhook trigger for tenant and user context + webhook_trigger: Webhook trigger for tenant context + end_user: Trigger end user that owns the file. The async workflow run executes as this + end user, and its file access scope only loads tool files the end user owns. Returns: Any: A file object built from the binary content @@ -447,7 +479,7 @@ def _create_file_from_binary( # Create file using ToolFileManager tool_file = tool_file_manager.create_file_by_raw( - user_id=webhook_trigger.created_by, + user_id=end_user.id, tenant_id=webhook_trigger.tenant_id, conversation_id=None, file_binary=file_content, @@ -836,12 +868,7 @@ def trigger_workflow_execution( tenant_id=webhook_trigger.tenant_id, ) - end_user = end_users.get_or_create_end_user_by_type( - type=EndUserType.TRIGGER, - tenant_id=webhook_trigger.tenant_id, - app_id=webhook_trigger.app_id, - user_id=None, - ) + end_user = cls._resolve_trigger_end_user(webhook_trigger, end_users) try: quota_charge = QuotaService.reserve(QuotaType.TRIGGER, webhook_trigger.tenant_id) diff --git a/api/tests/unit_tests/controllers/trigger/test_webhook.py b/api/tests/unit_tests/controllers/trigger/test_webhook.py index 8537780e1e2313..f1e16d9a3ffc27 100644 --- a/api/tests/unit_tests/controllers/trigger/test_webhook.py +++ b/api/tests/unit_tests/controllers/trigger/test_webhook.py @@ -1,14 +1,21 @@ from dataclasses import dataclass -from unittest.mock import patch +from io import BytesIO +from unittest.mock import MagicMock, patch import pytest +from flask import Flask from werkzeug.exceptions import NotFound, RequestEntityTooLarge import controllers.trigger.webhook as module +from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom +from core.app.file_access import DatabaseFileAccessController, FileAccessScope, bind_file_access_scope +from factories import file_factory +from models.enums import DEFAULT_END_USER_SESSION_ID, EndUserType +from models.model import EndUser from models.trigger import WorkflowWebhookTrigger from models.workflow import Workflow from services.errors.app import QuotaExceededError -from tests.helpers.unit.model_factories import make_workflow +from tests.helpers.unit.model_factories import make_end_user, make_workflow class _RequestStub: @@ -27,6 +34,22 @@ def __init__(self, commands: object) -> None: self.app_scoped_end_users = _AppScopedEndUserServicesStub(commands) +class _EndUserCommandsStub: + def __init__(self, end_user: EndUser) -> None: + self._end_user = end_user + self.calls: list[tuple[EndUserType, str, str, str | None]] = [] + + def get_or_create_end_user_by_type( + self, + type: EndUserType, + tenant_id: str, + app_id: str, + user_id: str | None = None, + ) -> EndUser: + self.calls.append((type, tenant_id, app_id, user_id)) + return self._end_user + + @pytest.fixture(autouse=True) def mock_request(): module.request = _RequestStub() @@ -83,6 +106,55 @@ def test_prepare_validation_error(self, mock_extract, mock_get): assert error == "bad" assert webhook_data["method"] == "POST" + @patch.object(module.WebhookService, "get_webhook_trigger_and_workflow") + def test_prepare_stores_uploads_for_the_trigger_end_user_run( + self, mock_get: MagicMock, app: Flask, monkeypatch: pytest.MonkeyPatch + ) -> None: + node_config = { + "data": { + "method": "post", + "content_type": "multipart/form-data", + "body": [{"name": "chat_history_file", "type": "file", "required": True}], + } + } + mock_get.return_value = (_webhook_trigger(), _workflow(), node_config) + trigger_end_user = make_end_user( + end_user_id="trigger-end-user-1", + tenant_id="tenant-1", + app_id="app-1", + end_user_type=EndUserType.TRIGGER, + session_id=DEFAULT_END_USER_SESSION_ID, + ) + end_users = _EndUserCommandsStub(trigger_end_user) + monkeypatch.setattr(module, "application_services", lambda: _ApplicationServicesStub(end_users)) + monkeypatch.setattr("core.tools.tool_file_manager.storage.save", lambda *_args: None) + + with app.test_request_context( + "/triggers/webhook/wh-1", + method="POST", + data={"chat_history_file": (BytesIO(b"# chat"), "chat.md", "text/markdown")}, + content_type="multipart/form-data", + ): + _, _, _, webhook_data, error = module._prepare_webhook_execution("wh-1") + + assert error is None + tool_file_id = webhook_data["files"]["chat_history_file"]["related_id"] + # The async run executes as the trigger end user, whose scope only loads tool files it owns. + run_scope = FileAccessScope( + tenant_id="tenant-1", + user_id=trigger_end_user.id, + user_from=UserFrom.END_USER, + invoke_from=InvokeFrom.SERVICE_API, + ) + with bind_file_access_scope(run_scope): + file = file_factory.build_from_mapping( + mapping={"transfer_method": "tool_file", "tool_file_id": tool_file_id}, + tenant_id="tenant-1", + access_controller=DatabaseFileAccessController(), + ) + assert file.related_id == tool_file_id + assert end_users.calls == [(EndUserType.TRIGGER, "tenant-1", "app-1", None)] + class TestHandleWebhook: @patch.object(module.WebhookService, "get_webhook_trigger_and_workflow") diff --git a/api/tests/unit_tests/services/trigger/test_webhook_service.py b/api/tests/unit_tests/services/trigger/test_webhook_service.py index 7e5ac49b18e9b3..04a6f3d0f8f7fd 100644 --- a/api/tests/unit_tests/services/trigger/test_webhook_service.py +++ b/api/tests/unit_tests/services/trigger/test_webhook_service.py @@ -132,6 +132,10 @@ def _end_user() -> EndUser: ) +def _end_users() -> _EndUserServiceStub: + return _EndUserServiceStub(_end_user()) + + class TestWebhookServiceCases: class TestWebhookServiceLookup: def test_debug_lookup_scopes_draft_workflow_to_trigger_owner( @@ -346,7 +350,7 @@ def test_extract_webhook_data_json(self): json={"message": "hello", "count": 42}, ): webhook_trigger = _webhook_trigger() - webhook_data = WebhookService.extract_webhook_data(webhook_trigger) + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) assert webhook_data["method"] == "POST" assert webhook_data["headers"]["Authorization"] == "Bearer token" @@ -368,7 +372,7 @@ def test_extract_webhook_data_query_params_remain_strings(self): query_string="count=42&threshold=3.14&enabled=true¬e=text", ): webhook_trigger = _webhook_trigger() - webhook_data = WebhookService.extract_webhook_data(webhook_trigger) + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) # After refactoring, raw extraction keeps query params as strings assert webhook_data["query_params"]["count"] == "42" @@ -387,7 +391,7 @@ def test_extract_webhook_data_form_urlencoded(self): data={"username": "test", "password": "secret"}, ): webhook_trigger = _webhook_trigger() - webhook_data = WebhookService.extract_webhook_data(webhook_trigger) + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) assert webhook_data["method"] == "POST" assert webhook_data["body"]["username"] == "test" @@ -413,7 +417,7 @@ def test_extract_webhook_data_multipart_with_files(self): with patch.object(WebhookService, "_process_file_uploads", autospec=True) as mock_process_files: mock_process_files.return_value = {"file": "mocked_file_obj"} - webhook_data = WebhookService.extract_webhook_data(webhook_trigger) + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) assert webhook_data["method"] == "POST" assert webhook_data["body"]["message"] == "test" @@ -428,7 +432,7 @@ def test_extract_webhook_data_raw_text(self): "/webhook", method="POST", headers={"Content-Type": "text/plain"}, data="raw text content" ): webhook_trigger = _webhook_trigger() - webhook_data = WebhookService.extract_webhook_data(webhook_trigger) + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) assert webhook_data["method"] == "POST" assert webhook_data["body"]["raw"] == "raw text content" @@ -442,6 +446,8 @@ def test_extract_octet_stream_body_uses_detected_mime(self): "/webhook", method="POST", headers={"Content-Type": "application/octet-stream"}, data=binary_content ): webhook_trigger = _webhook_trigger() + end_user = _end_user() + end_users = _EndUserServiceStub(end_user) mock_file = MagicMock() mock_file.to_dict.return_value = {"file": "data"} @@ -452,7 +458,7 @@ def test_extract_octet_stream_body_uses_detected_mime(self): patch.object(WebhookService, "_create_file_from_binary", autospec=True) as mock_create, ): mock_create.return_value = mock_file - body, files = WebhookService._extract_octet_stream_body(webhook_trigger) + body, files = WebhookService._extract_octet_stream_body(webhook_trigger, end_users) assert body["raw"] == {"file": "data"} assert files == {} @@ -462,6 +468,8 @@ def test_extract_octet_stream_body_uses_detected_mime(self): assert args[0] == binary_content assert args[1] == "text/plain" assert args[2] is webhook_trigger + assert args[3] is end_user + assert end_users.calls == [(EndUserType.TRIGGER, "tenant-123", "app-123", None)] def test_detect_binary_mimetype_uses_magic(self, monkeypatch: pytest.MonkeyPatch): """python-magic output should be used when available.""" @@ -510,7 +518,7 @@ def test_extract_webhook_data_invalid_json(self): ): webhook_trigger = _webhook_trigger() with pytest.raises(ValueError, match="Invalid JSON body"): - WebhookService.extract_webhook_data(webhook_trigger) + WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) def test_generate_webhook_response_default(self): """Test webhook response generation with default values.""" @@ -596,8 +604,9 @@ def test_process_file_uploads_success(self, mock_file_factory, mock_tool_file_ma webhook_trigger = _webhook_trigger() webhook_trigger.tenant_id = "test_tenant" + end_users = _end_users() - result = WebhookService._process_file_uploads(files, webhook_trigger) + result = WebhookService._process_file_uploads(files, webhook_trigger, end_users) assert len(result) == 2 assert "file1" in result @@ -606,6 +615,10 @@ def test_process_file_uploads_success(self, mock_file_factory, mock_tool_file_ma # Verify file processing was called for each file assert mock_tool_file_manager.call_count == 2 assert mock_file_factory.build_from_mapping.call_count == 2 + # Both files belong to the trigger end user, resolved once per request + assert end_users.calls == [(EndUserType.TRIGGER, "test_tenant", "app-123", None)] + create_calls = mock_tool_file_instance.create_file_by_raw.call_args_list + assert [call.kwargs["user_id"] for call in create_calls] == ["end-user-123", "end-user-123"] @patch("services.trigger.webhook_service.ToolFileManager", autospec=True) @patch("services.trigger.webhook_service.file_factory", autospec=True) @@ -631,7 +644,7 @@ def test_process_file_uploads_with_errors(self, mock_file_factory, mock_tool_fil webhook_trigger = _webhook_trigger() webhook_trigger.tenant_id = "test_tenant" - result = WebhookService._process_file_uploads(files, webhook_trigger) + result = WebhookService._process_file_uploads(files, webhook_trigger, _end_users()) # Should process the good file and skip the bad one assert len(result) == 1 @@ -648,7 +661,7 @@ def test_process_file_uploads_empty_filename(self): webhook_trigger = _webhook_trigger() webhook_trigger.tenant_id = "test_tenant" - result = WebhookService._process_file_uploads(files, webhook_trigger) + result = WebhookService._process_file_uploads(files, webhook_trigger, _end_users()) # Should skip files without filenames assert len(result) == 0 @@ -806,7 +819,9 @@ def test_extract_and_validate_webhook_data_success(self): } } - result = WebhookService.extract_and_validate_webhook_data(webhook_trigger, node_config) + result = WebhookService.extract_and_validate_webhook_data( + webhook_trigger, node_config, end_users=_end_users() + ) # Check that types are correctly converted assert result["query_params"]["count"] == 42 # Converted to int @@ -833,7 +848,9 @@ def test_extract_and_validate_webhook_data_invalid_json_error(self): } with pytest.raises(ValueError, match="Invalid JSON body"): - WebhookService.extract_and_validate_webhook_data(webhook_trigger, node_config) + WebhookService.extract_and_validate_webhook_data( + webhook_trigger, node_config, end_users=_end_users() + ) def test_extract_and_validate_webhook_data_validation_error(self): """Test unified data extraction with validation error.""" @@ -853,7 +870,9 @@ def test_extract_and_validate_webhook_data_validation_error(self): } with pytest.raises(ValueError, match="HTTP method mismatch"): - WebhookService.extract_and_validate_webhook_data(webhook_trigger, node_config) + WebhookService.extract_and_validate_webhook_data( + webhook_trigger, node_config, end_users=_end_users() + ) def test_extract_and_validate_webhook_request_missing_required_header(self) -> None: app = Flask(__name__) @@ -871,7 +890,9 @@ def test_extract_and_validate_webhook_request_missing_required_header(self) -> N } with pytest.raises(ValueError, match="Required header missing: Authorization"): - WebhookService.extract_and_validate_webhook_data(_webhook_trigger(), node_config) + WebhookService.extract_and_validate_webhook_data( + _webhook_trigger(), node_config, end_users=_end_users() + ) def test_extract_and_validate_webhook_request_case_insensitive_headers(self) -> None: app = Flask(__name__) @@ -890,7 +911,9 @@ def test_extract_and_validate_webhook_request_case_insensitive_headers(self) -> } } - result = WebhookService.extract_and_validate_webhook_data(_webhook_trigger(), node_config) + result = WebhookService.extract_and_validate_webhook_data( + _webhook_trigger(), node_config, end_users=_end_users() + ) assert result["headers"].get("Authorization") == "Bearer token" @@ -912,7 +935,9 @@ def test_extract_and_validate_webhook_request_missing_required_param(self) -> No } with pytest.raises(ValueError, match="Required parameter missing: version"): - WebhookService.extract_and_validate_webhook_data(_webhook_trigger(), node_config) + WebhookService.extract_and_validate_webhook_data( + _webhook_trigger(), node_config, end_users=_end_users() + ) def test_extract_and_validate_webhook_request_missing_required_body_param(self) -> None: app = Flask(__name__) @@ -931,7 +956,9 @@ def test_extract_and_validate_webhook_request_missing_required_body_param(self) } with pytest.raises(ValueError, match="Required body parameter missing: message"): - WebhookService.extract_and_validate_webhook_data(_webhook_trigger(), node_config) + WebhookService.extract_and_validate_webhook_data( + _webhook_trigger(), node_config, end_users=_end_users() + ) def test_extract_and_validate_webhook_request_missing_required_file(self) -> None: app = Flask(__name__) @@ -949,7 +976,9 @@ def test_extract_and_validate_webhook_request_missing_required_file(self) -> Non } } - result = WebhookService.extract_and_validate_webhook_data(_webhook_trigger(), node_config) + result = WebhookService.extract_and_validate_webhook_data( + _webhook_trigger(), node_config, end_users=_end_users() + ) assert result["files"] == {} @@ -961,6 +990,7 @@ def test_debug_mode_parameter_handling(self): with ( patch.object(WebhookService, "get_webhook_trigger_and_workflow", autospec=True) as mock_get_trigger, patch.object(WebhookService, "extract_and_validate_webhook_data", autospec=True) as mock_extract, + patch("controllers.trigger.webhook.application_services", autospec=True), ): webhook_trigger = _webhook_trigger() workflow = _workflow() @@ -1014,7 +1044,7 @@ def test_extract_webhook_data_should_use_text_fallback_for_unknown_content_type( headers={"Content-Type": "application/vnd.custom"}, data="plain content", ): - result = WebhookService.extract_webhook_data(webhook_trigger) + result = WebhookService.extract_webhook_data(webhook_trigger, end_users=_end_users()) assert result["body"] == {"raw": "plain content"} assert any(r.levelno >= logging.WARNING for r in caplog.records) @@ -1030,13 +1060,13 @@ def test_extract_webhook_data_should_raise_for_request_too_large( with flask_app.test_request_context("/webhook", method="POST", data="ab"): with pytest.raises(RequestEntityTooLarge): - WebhookService.extract_webhook_data(_workflow_trigger()) + WebhookService.extract_webhook_data(_workflow_trigger(), end_users=_end_users()) def test_extract_octet_stream_body_should_return_none_when_empty_payload(self, flask_app: Flask) -> None: webhook_trigger = _workflow_trigger() with flask_app.test_request_context("/webhook", method="POST", data=b""): - body, files = WebhookService._extract_octet_stream_body(webhook_trigger) + body, files = WebhookService._extract_octet_stream_body(webhook_trigger, _end_users()) assert body == {"raw": None} assert files == {} @@ -1053,7 +1083,7 @@ def test_extract_octet_stream_body_should_return_none_when_processing_raises( monkeypatch.setattr(WebhookService, "_create_file_from_binary", MagicMock(side_effect=RuntimeError("boom"))) with flask_app.test_request_context("/webhook", method="POST", data=b"abc"): - body, files = WebhookService._extract_octet_stream_body(webhook_trigger) + body, files = WebhookService._extract_octet_stream_body(webhook_trigger, _end_users()) assert body == {"raw": None} assert files == {} @@ -1098,7 +1128,7 @@ def test_process_file_uploads_should_use_octet_stream_fallback_when_mimetype_unk uploaded.content_type = None uploaded.read.return_value = b"content" - result = WebhookService._process_file_uploads({"f": uploaded}, webhook_trigger) + result = WebhookService._process_file_uploads({"f": uploaded}, webhook_trigger, _end_users()) assert result == {"f": {"id": "f-1"}} @@ -1115,10 +1145,11 @@ def test_create_file_from_binary_should_call_tool_file_manager_and_file_factory( service_module.file_factory, "build_from_mapping", MagicMock(return_value=expected_file) ) - result = WebhookService._create_file_from_binary(b"abc", "text/plain", webhook_trigger) + result = WebhookService._create_file_from_binary(b"abc", "text/plain", webhook_trigger, _end_user()) assert result is expected_file manager.create_file_by_raw.assert_called_once() + assert manager.create_file_by_raw.call_args.kwargs["user_id"] == "end-user-123" class TestWebhookServiceValidationAndConversion: @pytest.mark.parametrize( From 8ec0bdb5fb2357477dc06e26ae12087e878bdcf7 Mon Sep 17 00:00:00 2001 From: Tanishq Date: Sat, 31 Oct 2026 00:25:07 +0530 Subject: [PATCH 2/2] fix(trigger): reuse the request's trigger end user for the run The upload path and trigger_workflow_execution each looked the trigger end user up with get-or-create. end_users has no unique constraint, so a concurrent first request to a new app can create a second trigger end user in between, and the run was then queued under an end user that does not own this request's uploads. Keep the trigger end user resolved in a request in request-local context (flask.g, keyed by tenant and app) and reuse it for the run. Outside a request context nothing is cached. --- api/services/trigger/webhook_service.py | 25 ++++++- .../services/trigger/test_webhook_service.py | 70 ++++++++++++++++++- 2 files changed, 90 insertions(+), 5 deletions(-) diff --git a/api/services/trigger/webhook_service.py b/api/services/trigger/webhook_service.py index 85ce61bed9d6c8..28b2f0312fd460 100644 --- a/api/services/trigger/webhook_service.py +++ b/api/services/trigger/webhook_service.py @@ -7,7 +7,7 @@ from typing import Any, NotRequired, Protocol, TypedDict import orjson -from flask import request +from flask import g, has_request_context, request from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.orm import Session, sessionmaker @@ -50,6 +50,10 @@ logger = logging.getLogger(__name__) _file_access_controller = DatabaseFileAccessController() +# Request-local cache of the trigger end user resolved for each (tenant_id, app_id), so the files a +# webhook request uploads and the run it queues always share the same owner. +_TRIGGER_END_USER_CACHE_KEY = "_webhook_trigger_end_users" + class RawWebhookDataDict(TypedDict): method: str @@ -418,13 +422,28 @@ def _detect_binary_mimetype(file_content: bytes) -> str: def _resolve_trigger_end_user( webhook_trigger: WorkflowWebhookTrigger, end_users: WebhookEndUserProvisioner ) -> EndUser: - """Return the app's trigger end user, the identity that webhook workflow runs execute as.""" - return end_users.get_or_create_end_user_by_type( + """Return the app's trigger end user, the identity that webhook workflow runs execute as. + + Within a request, the end user is resolved once and reused from request-local context. A + second lookup could select another trigger end user that a concurrent request created in + the meantime, and the run would then not own the files this request uploaded. + """ + cache: dict[tuple[str, str], EndUser] | None = ( + g.setdefault(_TRIGGER_END_USER_CACHE_KEY, {}) if has_request_context() else None + ) + key = (webhook_trigger.tenant_id, webhook_trigger.app_id) + if cache is not None and key in cache: + return cache[key] + + end_user = end_users.get_or_create_end_user_by_type( type=EndUserType.TRIGGER, tenant_id=webhook_trigger.tenant_id, app_id=webhook_trigger.app_id, user_id=None, ) + if cache is not None: + cache[key] = end_user + return end_user @classmethod def _process_file_uploads( diff --git a/api/tests/unit_tests/services/trigger/test_webhook_service.py b/api/tests/unit_tests/services/trigger/test_webhook_service.py index 04a6f3d0f8f7fd..c347f51fab732f 100644 --- a/api/tests/unit_tests/services/trigger/test_webhook_service.py +++ b/api/tests/unit_tests/services/trigger/test_webhook_service.py @@ -53,6 +53,24 @@ def get_or_create_end_user_by_type( return self._result +class _EndUserSequenceStub: + """Returns the given end users one per lookup, then keeps returning the last one.""" + + def __init__(self, *results: EndUser) -> None: + self._results = results + self.calls: list[tuple[EndUserType, str, str, str | None]] = [] + + def get_or_create_end_user_by_type( + self, + type: EndUserType, + tenant_id: str, + app_id: str, + user_id: str | None = None, + ) -> EndUser: + self.calls.append((type, tenant_id, app_id, user_id)) + return self._results[min(len(self.calls), len(self._results)) - 1] + + def _webhook_trigger( *, webhook_id: str = "webhook-123", @@ -122,9 +140,9 @@ def _app_trigger(*, status: AppTriggerStatus = AppTriggerStatus.ENABLED) -> AppT ) -def _end_user() -> EndUser: +def _end_user(end_user_id: str = "end-user-123") -> EndUser: return make_end_user( - end_user_id="end-user-123", + end_user_id=end_user_id, tenant_id="tenant-123", app_id="app-123", end_user_type=EndUserType.TRIGGER, @@ -338,6 +356,54 @@ def test_trigger_workflow_execution_end_user_service_failure(self) -> None: end_users=_EndUserServiceStub(ValueError("Failed to create end user")), ) + def test_trigger_workflow_execution_reuses_the_end_user_that_owns_the_uploads(self) -> None: + # The request creates trigger end user B and uploads under it while a concurrent request + # commits trigger end user A, so a second lookup would select A. The run must stay with B, + # because only the file's owner can load it. + app = Flask(__name__) + webhook_trigger = _webhook_trigger() + upload_owner = _end_user("end-user-b") + concurrent_end_user = _end_user("end-user-a") + end_users = _EndUserSequenceStub(upload_owner, concurrent_end_user) + + with ( + app.test_request_context( + "/webhook", + method="POST", + headers={"Content-Type": "application/octet-stream"}, + data=b"payload", + ), + patch.object(WebhookService, "_detect_binary_mimetype", return_value="text/plain", autospec=True), + patch.object(WebhookService, "_create_file_from_binary", autospec=True) as mock_create, + patch.object(webhook_service_module, "db"), + patch.object(webhook_service_module.QuotaService, "reserve"), + patch.object(webhook_service_module.AsyncWorkflowService, "trigger_workflow_async") as mock_trigger, + ): + mock_create.return_value.to_dict.return_value = {"file": "data"} + webhook_data = WebhookService.extract_webhook_data(webhook_trigger, end_users=end_users) + WebhookService.trigger_workflow_execution( + webhook_trigger, webhook_data, _workflow(), end_users=end_users + ) + + assert mock_create.call_args[0][3] is upload_owner + assert mock_trigger.call_args[0][0] is upload_owner + assert end_users.calls == [(EndUserType.TRIGGER, "tenant-123", "app-123", None)] + + def test_trigger_end_user_is_looked_up_again_in_the_next_request(self) -> None: + app = Flask(__name__) + webhook_trigger = _webhook_trigger() + first_end_user = _end_user("end-user-1") + second_end_user = _end_user("end-user-2") + end_users = _EndUserSequenceStub(first_end_user, second_end_user) + + with app.test_request_context("/webhook", method="POST"): + assert WebhookService._resolve_trigger_end_user(webhook_trigger, end_users) is first_end_user + assert WebhookService._resolve_trigger_end_user(webhook_trigger, end_users) is first_end_user + with app.test_request_context("/webhook", method="POST"): + assert WebhookService._resolve_trigger_end_user(webhook_trigger, end_users) is second_end_user + + assert len(end_users.calls) == 2 + def test_extract_webhook_data_json(self): """Test webhook data extraction from JSON request.""" app = Flask(__name__)