Skip to content

armgit / dify

Public Imported from GitHub
0

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.

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.py
index 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 ResponseModel
from libs.external_api import error_responses
from libs.helper import RateLimiter, dump_response, extract_remote_ip, to_timestamp
from models.account import TenantStatus
+from models.human_input import RecipientType
from models.model import App, AppMode, Site
from services.feature_service import FeatureService
from 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.py
index 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 Session
from werkzeug.exceptions import Forbidden
import controllers.web.human_input_form as human_input_module
+from controllers.common.errors import NotFoundError
from 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, ValueSourceType
from models import Tenant
from models.account import TenantStatus
from models.enums import CustomizeTokenStrategy
from models.human_input import RecipientType
from models.model import App, AppMode, IconType, Site
from services.entities.feature_entities import FeatureModel
-from services.human_input_service import FormExpiredError
+from services.human_input_service import Form, FormExpiredError
HumanInputFormApi = human_input_module.HumanInputFormApi
HumanInputFormUploadTokenApi = human_input_module.HumanInputFormUploadTokenApi
@@ -98,7 +105,40 @@ def _persist_app_site(session: Session, *, include_site: bool = True) -> tuple[T
return 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, dat
self.app_id = app_model.id
self.tenant_id = app_model.tenant_id
self.expiration_time = expiration
- self.recipient_type = RecipientType.BACKSTAGE
+ self.recipient_type = recipient_type
def get_definition(self):
return _FakeDefinition()
@@ -269,9 +309,16 @@ def test_get_form_uses_runtime_select_options(monkeypatch: pytest.MonkeyPatch, a
service_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: pyte
limiter_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: F
self.app_id = app_model.id
self.tenant_id = app_model.tenant_id
self.expiration_time = expiration
+ self.recipient_type = recipient_type
def 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 = None
self.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 = None
self.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 = False
monkeypatch.setattr(human_input_module, "_FORM_SUBMIT_RATE_LIMITER", limiter_mock)
@@ -510,7 +521,7 @@ def test_submit_form_accepts_backstage_token(monkeypatch: pytest.MonkeyPatch, ap
assert status == 200
assert 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_APP
pass
form = _FakeForm()
@@ -588,3 +600,37 @@ def test_get_form_raises_expired(monkeypatch: pytest.MonkeyPatch, app: Flask, sq
service_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")