Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(web-api): reject internal approval tokens on public HITL endpoints (#44644)
Winorenb1d2e2983b7c
diff --git a/api/controllers/web/human_input_form.py b/api/controllers/web/human_input_form.pyindex 67d0285146c..e5c181a3503 100644--- a/api/controllers/web/human_input_form.py+++ b/api/controllers/web/human_input_form.py@@ -26,6 +26,7 @@ from fields.base import ResponseModelfrom libs.external_api import error_responsesfrom libs.helper import RateLimiter, dump_response, extract_remote_ip, to_timestampfrom models.account import TenantStatus+from models.human_input import RecipientTypefrom models.model import App, AppMode, Sitefrom services.feature_service import FeatureServicefrom services.human_input_service import (@@ -137,6 +138,7 @@ class HumanInputFormUploadTokenApi(Resource):raise WebFormRateLimitExceededError()_FORM_UPLOAD_TOKEN_RATE_LIMITER.increment_rate_limit(ip_address)+ _get_public_form_by_token(HumanInputService(db.engine), form_token)try:token = application_services().human_input_file_uploads.issue_upload_token(form_token)except FormNotFoundError as caught_error:@@ -183,12 +185,7 @@ class HumanInputFormApi(Resource):_FORM_ACCESS_RATE_LIMITER.increment_rate_limit(ip_address)service = HumanInputService(db.engine)- # TODO(QuantumGhost): forbid submission for form tokens- # that are only for console.- form = service.get_form_by_token(form_token)-- if form is None:- raise NotFoundError("Form not found")+ form = _get_public_form_by_token(service, form_token)service.ensure_form_active(form)app_model, site = _get_app_site_from_form(form)@@ -255,9 +252,7 @@ class HumanInputFormApi(Resource):_FORM_SUBMIT_RATE_LIMITER.increment_rate_limit(ip_address)service = HumanInputService(db.engine)- form = service.get_form_by_token(form_token)- if form is None:- raise NotFoundError("Form not found")+ form = _get_public_form_by_token(service, form_token)if (recipient_type := form.recipient_type) is None:logger.warning("Recipient type is None for form, form_id=%s", form.id)@@ -277,6 +272,22 @@ class HumanInputFormApi(Resource):return HumanInputFormSubmitResponse().model_dump(mode="json"), 200+def _get_public_form_by_token(service: HumanInputService, form_token: str) -> Form:+ """Reject internal Console/Backstage tokens before public form operations.++ Email delivery links also use this Web API, so email recipients remain+ allowed alongside standalone Web App recipients.+ """+ form = service.get_form_by_token(form_token)+ if form is None or form.recipient_type not in {+ RecipientType.STANDALONE_WEB_APP,+ RecipientType.EMAIL_MEMBER,+ RecipientType.EMAIL_EXTERNAL,+ }:+ raise NotFoundError("Form not found")+ return form++def _get_app_site_from_form(form: Form) -> tuple[App, Site]:"""Resolve App/Site for the form's app and validate tenant status."""app_model = db.session.get(App, form.app_id)diff --git a/api/tests/unit_tests/controllers/web/test_human_input_form.py b/api/tests/unit_tests/controllers/web/test_human_input_form.pyindex 7e10c48abbc..408660b62f1 100644--- a/api/tests/unit_tests/controllers/web/test_human_input_form.py+++ b/api/tests/unit_tests/controllers/web/test_human_input_form.py@@ -14,16 +14,23 @@ from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbiddenimport controllers.web.human_input_form as human_input_module+from controllers.common.errors import NotFoundErrorfrom controllers.web.error import WebFormRateLimitExceededError-from core.workflow.nodes.human_input.entities import ParagraphInputConfig, SelectInputConfig, StringListSource-from core.workflow.nodes.human_input.enums import ValueSourceType+from core.repositories.human_input_repository import HumanInputFormRecord+from core.workflow.nodes.human_input.entities import (+ FormDefinition,+ ParagraphInputConfig,+ SelectInputConfig,+ StringListSource,+)+from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceTypefrom models import Tenantfrom models.account import TenantStatusfrom models.enums import CustomizeTokenStrategyfrom models.human_input import RecipientTypefrom models.model import App, AppMode, IconType, Sitefrom services.entities.feature_entities import FeatureModel-from services.human_input_service import FormExpiredError+from services.human_input_service import Form, FormExpiredErrorHumanInputFormApi = human_input_module.HumanInputFormApiHumanInputFormUploadTokenApi = human_input_module.HumanInputFormUploadTokenApi@@ -98,7 +105,40 @@ def _persist_app_site(session: Session, *, include_site: bool = True) -> tuple[Treturn tenant, app_model, site-def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask, database_session: Session):+def _public_form(recipient_type: RecipientType) -> Form:+ expiration = datetime(2099, 1, 1, tzinfo=UTC)+ return Form(+ HumanInputFormRecord(+ form_id="form-id",+ workflow_run_id=None,+ node_id="node-id",+ tenant_id="tenant-id",+ app_id="app-id",+ form_kind=HumanInputFormKind.DELIVERY_TEST,+ definition=FormDefinition(form_content="Approve", rendered_content="Approve", expiration_time=expiration),+ rendered_content="Approve",+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ expiration_time=expiration,+ status=HumanInputFormStatus.WAITING,+ selected_action_id=None,+ submitted_data=None,+ submitted_at=None,+ submission_user_id=None,+ submission_end_user_id=None,+ completed_by_recipient_id=None,+ recipient_id="recipient-id",+ recipient_type=recipient_type,+ access_token="token-1",+ )+ )+++ "recipient_type", [RecipientType.STANDALONE_WEB_APP, RecipientType.EMAIL_MEMBER, RecipientType.EMAIL_EXTERNAL]+)+def test_get_form_includes_site(+ monkeypatch: pytest.MonkeyPatch, app: Flask, database_session: Session, recipient_type: RecipientType+) -> None:"""GET returns form definition merged with site payload."""expiration_time = datetime(2099, 1, 1, tzinfo=UTC)@@ -120,7 +160,7 @@ def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask, datself.app_id = app_model.idself.tenant_id = app_model.tenant_idself.expiration_time = expiration- self.recipient_type = RecipientType.BACKSTAGE+ self.recipient_type = recipient_typedef get_definition(self):return _FakeDefinition()@@ -269,9 +309,16 @@ def test_get_form_uses_runtime_select_options(monkeypatch: pytest.MonkeyPatch, aservice_mock.resolve_form_inputs.assert_called_once_with(form)-def test_create_upload_token_returns_token_and_form_expiration(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None:+ "recipient_type", [RecipientType.STANDALONE_WEB_APP, RecipientType.EMAIL_MEMBER, RecipientType.EMAIL_EXTERNAL]+)+def test_create_upload_token_returns_token_and_form_expiration(+ monkeypatch: pytest.MonkeyPatch, app: Flask, database_session: Session, recipient_type: RecipientType+) -> None:"""POST returns a HITL upload token for an active form token."""+ form = _public_form(recipient_type)+ monkeypatch.setattr(human_input_module.HumanInputService, "get_form_by_token", lambda self, token: form)expiration_time = datetime(2099, 1, 1, tzinfo=UTC)service_mock = MagicMock()service_mock.issue_upload_token.return_value = SimpleNamespace(@@ -301,8 +348,11 @@ def test_create_upload_token_returns_token_and_form_expiration(monkeypatch: pytelimiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10")-def test_get_form_allows_backstage_token(monkeypatch: pytest.MonkeyPatch, app: Flask, database_session: Session):- """GET returns form payload for backstage token."""[email protected]("recipient_type", [RecipientType.CONSOLE, RecipientType.BACKSTAGE])+def test_get_form_rejects_internal_tokens(+ monkeypatch: pytest.MonkeyPatch, app: Flask, database_session: Session, recipient_type: RecipientType+) -> None:+ """Internal approval tokens cannot disclose a form through the public Web API."""expiration_time = datetime(2099, 1, 2, tzinfo=UTC)_, app_model, _ = _persist_app_site(database_session)@@ -323,6 +373,7 @@ def test_get_form_allows_backstage_token(monkeypatch: pytest.MonkeyPatch, app: Fself.app_id = app_model.idself.tenant_id = app_model.tenant_idself.expiration_time = expiration+ self.recipient_type = recipient_typedef get_definition(self):return _FakeDefinition()@@ -344,56 +395,10 @@ def test_get_form_allows_backstage_token(monkeypatch: pytest.MonkeyPatch, app: F)with app.test_request_context("/api/form/human_input/token-1", method="GET"):- response = HumanInputFormApi().get("token-1")-- body = response- assert set(body.keys()) == {- "site",- "form_content",- "inputs",- "resolved_default_values",- "user_actions",- "expiration_time",- }- assert body["form_content"] == "Rendered"- assert body["inputs"] == []- assert body["resolved_default_values"] == {}- assert body["user_actions"] == []- assert body["expiration_time"] == int(expiration_time.timestamp())- assert body["site"] == {- "app_id": app_model.id,- "mode": "chat",- "end_user_id": None,- "enable_site": True,- "site": {- "title": "My Site",- "chat_color_theme": "light",- "chat_color_theme_inverted": False,- "icon_type": "emoji",- "icon": "robot",- "icon_background": "#fff",- "icon_url": None,- "description": "desc",- "copyright": None,- "privacy_policy": None,- "input_placeholder": "Ask the app",- "custom_disclaimer": "",- "default_language": "en",- "prompt_public": False,- "show_workflow_steps": True,- "use_icon_as_answer_icon": False,- },- "model_config": None,- "plan": "basic",- "can_replace_logo": True,- "custom_config": {- "remove_webapp_brand": True,- "replace_webapp_logo": None,- },- }- service_mock.get_form_by_token.assert_called_once_with("token-1")- limiter_mock.is_rate_limited.assert_called_once_with("203.0.113.10")- limiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10")+ with pytest.raises(NotFoundError):+ HumanInputFormApi().get("token-1")+ service_mock.ensure_form_active.assert_not_called()+ service_mock.resolve_form_inputs.assert_not_called()def test_get_form_raises_forbidden_when_site_missing(@@ -415,6 +420,8 @@ def test_get_form_raises_forbidden_when_site_missing(}class _FakeForm:+ recipient_type = RecipientType.STANDALONE_WEB_APP+def __init__(self, expiration: datetime):self.workflow_run_id = Noneself.app_id = app_model.id@@ -461,6 +468,8 @@ def test_get_form_raises_forbidden_when_tenant_archived(}class _FakeForm:+ recipient_type = RecipientType.STANDALONE_WEB_APP+def __init__(self, expiration: datetime) -> None:self.workflow_run_id: str | None = Noneself.app_id: str = app_model.id@@ -484,13 +493,15 @@ def test_get_form_raises_forbidden_when_tenant_archived(HumanInputFormApi().get("token-1")-def test_submit_form_accepts_backstage_token(monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine):- """POST forwards backstage submissions to the service."""-- class _FakeForm:- recipient_type = RecipientType.BACKSTAGE+ "recipient_type", [RecipientType.STANDALONE_WEB_APP, RecipientType.EMAIL_MEMBER, RecipientType.EMAIL_EXTERNAL]+)+def test_submit_form_accepts_public_tokens(+ monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine, recipient_type: RecipientType+) -> None:+ """Web and email approval links can still submit through the public API."""- form = _FakeForm()+ form = _public_form(recipient_type)limiter_mock = MagicMock()limiter_mock.is_rate_limited.return_value = Falsemonkeypatch.setattr(human_input_module, "_FORM_SUBMIT_RATE_LIMITER", limiter_mock)@@ -510,7 +521,7 @@ def test_submit_form_accepts_backstage_token(monkeypatch: pytest.MonkeyPatch, apassert status == 200assert response == {}service_mock.submit_form_by_token.assert_called_once_with(- recipient_type=RecipientType.BACKSTAGE,+ recipient_type=recipient_type,form_token="token-1",selected_action_id="approve",form_data={"content": "ok"},@@ -568,6 +579,7 @@ def test_get_form_rate_limited(monkeypatch: pytest.MonkeyPatch, app: Flask):def test_get_form_raises_expired(monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine):class _FakeForm:+ recipient_type = RecipientType.STANDALONE_WEB_APPpassform = _FakeForm()@@ -588,3 +600,37 @@ def test_get_form_raises_expired(monkeypatch: pytest.MonkeyPatch, app: Flask, sqservice_mock.ensure_form_active.assert_called_once_with(form)limiter_mock.is_rate_limited.assert_called_once_with("203.0.113.10")limiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10")++[email protected]("recipient_type", [RecipientType.CONSOLE, RecipientType.BACKSTAGE])[email protected]("endpoint", ["submit", "upload-token"])+def test_public_mutations_reject_internal_tokens(+ monkeypatch: pytest.MonkeyPatch,+ app: Flask,+ database_session: Session,+ recipient_type: RecipientType,+ endpoint: str,+) -> None:+ form = _public_form(recipient_type)+ monkeypatch.setattr(human_input_module.HumanInputService, "get_form_by_token", lambda self, token: form)+ monkeypatch.setattr(+ human_input_module.HumanInputService,+ "submit_form_by_token",+ lambda *args, **kwargs: pytest.fail("Internal tokens must not reach form submission"),+ )+ monkeypatch.setattr(+ human_input_module,+ "application_services",+ lambda: pytest.fail("Internal tokens must not reach upload-token issuance"),+ )+ for limiter in [human_input_module._FORM_SUBMIT_RATE_LIMITER, human_input_module._FORM_UPLOAD_TOKEN_RATE_LIMITER]:+ monkeypatch.setattr(limiter, "is_rate_limited", lambda address: False)+ monkeypatch.setattr(limiter, "increment_rate_limit", lambda address: None)+ monkeypatch.setattr(human_input_module, "extract_remote_ip", lambda req: "203.0.113.10")++ with app.test_request_context(+ "/api/form/human_input/token-1", method="POST", json={"inputs": {}, "action": "approve"}+ ):+ api = HumanInputFormApi() if endpoint == "submit" else HumanInputFormUploadTokenApi()+ with pytest.raises(NotFoundError):+ api.post("token-1")