Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion api/controllers/trigger/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 68 additions & 22 deletions api/services/trigger/webhook_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -182,13 +186,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
Expand All @@ -197,7 +206,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)
Expand All @@ -211,11 +220,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:
Expand All @@ -242,8 +254,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,
}

Expand Down Expand Up @@ -332,29 +344,33 @@ 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:
- body_data: Form data as key-value pairs
- 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:
Expand All @@ -365,7 +381,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}, {}
Expand Down Expand Up @@ -401,27 +418,59 @@ 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.

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(
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)
Expand All @@ -431,14 +480,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
Expand All @@ -447,7 +498,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,
Expand Down Expand Up @@ -854,12 +905,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)
Comment thread
Stream29 marked this conversation as resolved.
Resolved

try:
quota_charge = QuotaService.reserve(QuotaType.TRIGGER, webhook_trigger.tenant_id)
Expand Down
81 changes: 79 additions & 2 deletions api/tests/unit_tests/controllers/trigger/test_webhook.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
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 sqlalchemy.orm import Session, sessionmaker
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 repositories.trigger.app_repository import SQLAlchemyAppTriggerRepository
from services.errors.app import QuotaExceededError
from services.trigger.app_trigger_service import AppTriggerService
from tests.helpers.unit.model_factories import make_workflow
from tests.helpers.unit.model_factories import make_end_user, make_workflow


class _RequestStub:
Expand Down Expand Up @@ -42,6 +49,22 @@ def __init__(self, commands: object, trigger_status: AppTriggerService) -> None:
self.workspaces = _WorkspaceServicesStub(object())


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()
Expand Down Expand Up @@ -99,6 +122,60 @@ 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,
sqlite_session_factory: sessionmaker[Session],
) -> 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)
triggers = AppTriggerService(triggers=SQLAlchemyAppTriggerRepository(session_factory=sqlite_session_factory))
monkeypatch.setattr(module, "application_services", lambda: _ApplicationServicesStub(end_users, triggers))
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")
Expand Down
Loading