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.

feat(dify-agent): enforce signed upload size limits (#40883)

盐粒 Yanli2aaac4dadb6d
diff --git a/api/controllers/files/upload.py b/api/controllers/files/upload.py
index 82a7ae4fb65..aac1c3b20c8 100644
--- a/api/controllers/files/upload.py
+++ b/api/controllers/files/upload.py
@@ -32,6 +32,7 @@ class PluginUploadQuery(BaseModel):
user_id: str | None = Field(default=None, description="User identifier")
user_from: Literal["account", "end-user"] | None = Field(default=None, description="User identity type")
conversation_id: str | None = Field(default=None, description="Conversation identifier")
+ max_size: int | None = Field(default=None, ge=0, description="Signed maximum file size in bytes")
register_schema_models(files_ns, PluginUploadQuery)
@@ -113,14 +114,22 @@ class PluginUploadFileApi(Resource):
timestamp=timestamp,
nonce=nonce,
sign=sign,
+ max_size=args.max_size,
):
raise Forbidden("Invalid request.")
try:
+ if args.max_size is None:
+ file_binary = file.stream.read()
+ else:
+ file_binary = file.stream.read(args.max_size + 1)
+ if len(file_binary) > args.max_size:
+ raise FileTooLargeError("File size exceeds the signed upload limit.")
+
tool_file = ToolFileManager().create_file_by_raw(
user_id=owner_id,
tenant_id=tenant_id,
- file_binary=file.stream.read(),
+ file_binary=file_binary,
mimetype=mimetype,
filename=filename,
conversation_id=args.conversation_id,
diff --git a/api/controllers/inner_api/agent/files.py b/api/controllers/inner_api/agent/files.py
index 8838ba2d4fe..d4e224622f7 100644
--- a/api/controllers/inner_api/agent/files.py
+++ b/api/controllers/inner_api/agent/files.py
@@ -5,7 +5,7 @@ from __future__ import annotations
from typing import Literal
from flask_restx import Resource
-from pydantic import BaseModel, ConfigDict, ValidationError
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
from sqlalchemy.orm import Session
from configs import dify_config
@@ -39,6 +39,7 @@ class AgentFileUploadRequestPayload(RequestRequestUploadFile):
tenant_id: str
user_id: str
user_from: Literal["account", "end-user"] | None = None
+ max_size: int = Field(ge=0, description="Maximum upload size in bytes")
model_config = ConfigDict(extra="forbid")
@@ -127,6 +128,7 @@ class AgentFileUploadRequestApi(Resource):
user_id=owner_id,
conversation_id=payload.conversation_id,
user_from=payload.user_from,
+ max_size=payload.max_size,
)
except ValueError as exc:
raise AgentFileRequestHttpError(
diff --git a/api/core/tools/signature.py b/api/core/tools/signature.py
index 725160aaf8a..fc5a7642ac5 100644
--- a/api/core/tools/signature.py
+++ b/api/core/tools/signature.py
@@ -1,6 +1,7 @@
import base64
import hashlib
import hmac
+import json
import os
import time
import urllib.parse
@@ -95,6 +96,7 @@ def get_signed_file_uri_for_plugin(
user_id: str,
conversation_id: str | None = None,
user_from: Literal["account", "end-user"] | None = None,
+ max_size: int | None = None,
) -> str:
"""Build a signed plugin-upload URI without selecting a network origin."""
@@ -109,6 +111,7 @@ def get_signed_file_uri_for_plugin(
timestamp=timestamp,
nonce=nonce,
user_from=user_from,
+ max_size=max_size,
)
sign = hmac.new(_secret_key(), data_to_sign.encode(), hashlib.sha256).digest()
encoded_sign = base64.urlsafe_b64encode(sign).decode()
@@ -123,6 +126,8 @@ def get_signed_file_uri_for_plugin(
query_params["conversation_id"] = conversation_id
if user_from is not None:
query_params["user_from"] = user_from
+ if max_size is not None:
+ query_params["max_size"] = str(max_size)
query = urllib.parse.urlencode(query_params)
return f"/files/upload/for-plugin?{query}"
@@ -138,6 +143,7 @@ def verify_plugin_file_signature(
timestamp: str,
nonce: str,
sign: str,
+ max_size: int | None = None,
) -> bool:
"""Verify the signature used by the plugin-facing file upload endpoint."""
@@ -150,6 +156,7 @@ def verify_plugin_file_signature(
timestamp=timestamp,
nonce=nonce,
user_from=user_from,
+ max_size=max_size,
)
recalculated_sign = hmac.new(_secret_key(), data_to_sign.encode(), hashlib.sha256).digest()
recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
@@ -171,14 +178,34 @@ def _plugin_upload_signature_payload(
timestamp: str,
nonce: str,
user_from: Literal["account", "end-user"] | None,
+ max_size: int | None,
) -> str:
- """Build the compatible upload signature payload with optional identity ownership.
+ """Build the compatible upload signature payload with optional protected claims.
- Omitting ``user_from`` preserves the legacy payload. When present, the
- identity kind is appended and HMAC-protected so account/end-user ownership
- cannot be altered.
+ Omitting ``max_size`` preserves the legacy payload. Size-limited tickets use
+ a versioned JSON payload so unconstrained string fields cannot absorb or
+ impersonate optional trailing claims.
"""
+ if max_size is not None:
+ return json.dumps(
+ {
+ "conversation_id": conversation_id or "",
+ "filename": filename,
+ "max_size": max_size,
+ "mimetype": mimetype,
+ "nonce": nonce,
+ "tenant_id": tenant_id,
+ "timestamp": timestamp,
+ "user_from": user_from,
+ "user_id": user_id,
+ "version": 2,
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+
payload = f"upload|{filename}|{mimetype}|{tenant_id}|{user_id}|{conversation_id or ''}|{timestamp}|{nonce}"
if user_from is not None:
payload = f"{payload}|{user_from}"
diff --git a/api/tests/unit_tests/controllers/files/test_upload.py b/api/tests/unit_tests/controllers/files/test_upload.py
index fdbad62d593..dec841e35fd 100644
--- a/api/tests/unit_tests/controllers/files/test_upload.py
+++ b/api/tests/unit_tests/controllers/files/test_upload.py
@@ -2,7 +2,7 @@ import io
import types
from contextlib import contextmanager
from inspect import unwrap
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
import pytest
from sqlalchemy.orm import Session
@@ -206,6 +206,7 @@ class TestPluginUploadFileApi:
timestamp="123",
nonce="abc",
sign="sig",
+ max_size=None,
)
tool_file_manager.create_file_by_raw.assert_called_once_with(
user_id="account-1",
@@ -336,6 +337,65 @@ class TestPluginUploadFileApi:
with pytest.raises(module.FileTooLargeError):
post_fn(api)
+ @patch.object(module, "get_user", return_value=_end_user())
+ @patch.object(module, "verify_plugin_file_signature", return_value=True)
+ @patch.object(module, "ToolFileManager")
+ def test_signed_max_size_bounds_file_read(
+ self,
+ mock_tool_file_manager,
+ mock_verify,
+ mock_get_user,
+ ):
+ dummy_file = DummyFile(content=b"data")
+ dummy_file.stream = MagicMock()
+ dummy_file.stream.read.return_value = b"data"
+ module.request = fake_request(
+ {
+ "timestamp": "123",
+ "nonce": "abc",
+ "sign": "sig",
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "max_size": "4",
+ },
+ file=dummy_file,
+ )
+ mock_tool_file_manager.return_value.create_file_by_raw.return_value = _tool_file()
+ mock_tool_file_manager.sign_file.return_value = "signed-url"
+
+ unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
+
+ dummy_file.stream.read.assert_called_once_with(5)
+ assert mock_verify.call_args.kwargs["max_size"] == 4
+ assert mock_tool_file_manager.return_value.create_file_by_raw.call_args.kwargs["file_binary"] == b"data"
+
+ @patch.object(module, "get_user", return_value=_end_user())
+ @patch.object(module, "verify_plugin_file_signature", return_value=True)
+ @patch.object(module, "ToolFileManager")
+ def test_signed_max_size_rejects_oversized_file_before_creation(
+ self,
+ mock_tool_file_manager,
+ mock_verify,
+ mock_get_user,
+ ):
+ dummy_file = DummyFile(content=b"oversized")
+ module.request = fake_request(
+ {
+ "timestamp": "123",
+ "nonce": "abc",
+ "sign": "sig",
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "max_size": "4",
+ },
+ file=dummy_file,
+ )
+
+ with pytest.raises(module.FileTooLargeError):
+ unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
+
+ mock_tool_file_manager.assert_not_called()
+
@patch.object(module, "get_user", return_value=_end_user())
@patch.object(module, "verify_plugin_file_signature", return_value=True)
@patch.object(module, "ToolFileManager")
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
index d6a90456129..8a7d970a889 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from controllers.inner_api.agent.files import (
AgentFileDownloadRequestApi,
AgentFileUploadRequestApi,
+ AgentFileUploadRequestPayload,
)
from core.workflow.file_reference import build_file_reference
from services.file_request_service import DownloadFileRequestResult
@@ -29,6 +30,7 @@ def test_upload_request_returns_origin_free_uri(app: Flask, unbound_session: Ses
"filename": "report.pdf",
"mimetype": "application/pdf",
"conversation_id": "conversation-1",
+ "max_size": 64 * 1024 * 1024,
}
tenant = SimpleNamespace(id="tenant-1")
user = SimpleNamespace(id="canonical-end-user-1")
@@ -51,9 +53,26 @@ def test_upload_request_returns_origin_free_uri(app: Flask, unbound_session: Ses
user_id="canonical-end-user-1",
conversation_id="conversation-1",
user_from=None,
+ max_size=64 * 1024 * 1024,
)
+def test_upload_request_payload_requires_non_negative_max_size() -> None:
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "filename": "report.pdf",
+ "mimetype": "application/pdf",
+ }
+
+ with pytest.raises(ValueError):
+ AgentFileUploadRequestPayload.model_validate(payload)
+ with pytest.raises(ValueError):
+ AgentFileUploadRequestPayload.model_validate({**payload, "max_size": -1})
+
+ assert AgentFileUploadRequestPayload.model_validate({**payload, "max_size": 0}).max_size == 0
+
+
def test_download_request_returns_origin_free_uri_for_sandbox(app: Flask, unbound_session: Session) -> None:
reference = build_file_reference(record_id="tool-file-1")
payload = {
diff --git a/api/tests/unit_tests/core/tools/test_signature.py b/api/tests/unit_tests/core/tools/test_signature.py
index 142b82902bf..4985fc16368 100644
--- a/api/tests/unit_tests/core/tools/test_signature.py
+++ b/api/tests/unit_tests/core/tools/test_signature.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from typing import Literal
from urllib.parse import parse_qs, urlparse
import pytest
@@ -172,6 +173,7 @@ def test_get_signed_file_uri_for_plugin_and_verify_roundtrip(monkeypatch: pytest
assert query["tenant_id"] == ["tenant-id"]
assert query["user_id"] == ["user-id"]
assert query["conversation_id"] == ["conversation-id"]
+ assert "max_size" not in query
assert (
verify_plugin_file_signature(
filename="report.pdf",
@@ -187,6 +189,50 @@ def test_get_signed_file_uri_for_plugin_and_verify_roundtrip(monkeypatch: pytest
)
+ ("user_from", "forged_nonce_suffix"),
+ [
+ (None, "|1024"),
+ ("account", "|account|1024"),
+ ],
+)
+def test_plugin_upload_signature_binds_max_size_without_legacy_payload_ambiguity(
+ monkeypatch: pytest.MonkeyPatch,
+ user_from: Literal["account", "end-user"] | None,
+ forged_nonce_suffix: str,
+) -> None:
+ monkeypatch.setattr("core.tools.signature.time.time", lambda: 1700000000)
+ monkeypatch.setattr("core.tools.signature.os.urandom", lambda _: b"\x0a" * 16)
+ monkeypatch.setattr("core.tools.signature.dify_config.SECRET_KEY", "unit-secret")
+ monkeypatch.setattr("core.tools.signature.dify_config.FILES_ACCESS_TIMEOUT", 60)
+
+ uri = get_signed_file_uri_for_plugin(
+ filename="report.pdf",
+ mimetype="application/pdf",
+ tenant_id="tenant-id",
+ user_id="user-id",
+ user_from=user_from,
+ max_size=1024,
+ )
+ query = parse_qs(urlparse(uri).query)
+ signed = {
+ "filename": "report.pdf",
+ "mimetype": "application/pdf",
+ "tenant_id": "tenant-id",
+ "user_id": "user-id",
+ "timestamp": query["timestamp"][0],
+ "nonce": query["nonce"][0],
+ "sign": query["sign"][0],
+ }
+
+ assert query["max_size"] == ["1024"]
+ assert verify_plugin_file_signature(**signed, user_from=user_from, max_size=1024) is True
+ assert verify_plugin_file_signature(**signed, user_from=user_from, max_size=2048) is False
+ assert verify_plugin_file_signature(**signed, user_from=user_from) is False
+ forged = {**signed, "nonce": f"{signed['nonce']}{forged_nonce_suffix}"}
+ assert verify_plugin_file_signature(**forged) is False
+
+
def test_plugin_upload_signature_binds_account_user_from(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("core.tools.signature.time.time", lambda: 1700000000)
monkeypatch.setattr("core.tools.signature.os.urandom", lambda _: b"\x09" * 16)
diff --git a/dify-agent/.example.env b/dify-agent/.example.env
index 80efaf1692c..44c20ad0432 100644
--- a/dify-agent/.example.env
+++ b/dify-agent/.example.env
@@ -58,6 +58,8 @@ DIFY_AGENT_STUB_API_BASE_URL=http://localhost:5050/agent-stub
# Dify API base URL reachable from the Sandbox for the signed /files/* data plane,
# including Config file and skill pulls.
DIFY_AGENT_SANDBOX_FILES_BASE_URL=http://localhost:5001
+# Maximum Agent Stub upload size in MiB; forwarded to Dify API as a signed byte limit.
+DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT=50
# Server-wide root secret used to derive Agent Stub JWE keys.
# This is security-sensitive: it derives the JWE encryption key for Agent Stub bearer tokens.
# Replace this development default in production.
diff --git a/dify-agent/docs/dify-agent/guide/index.md b/dify-agent/docs/dify-agent/guide/index.md
index f24fd846e76..68a69772984 100644
--- a/dify-agent/docs/dify-agent/guide/index.md
+++ b/dify-agent/docs/dify-agent/guide/index.md
@@ -58,6 +58,7 @@ also reads `.env` and `dify-agent/.env` when present.
| `DIFY_AGENT_SHELL_REDACT_PATTERNS` | empty | JSON array of additional regex patterns redacted from Shell output. |
| `DIFY_AGENT_STUB_API_BASE_URL` | empty | HTTP(S) Agent Stub API base URL reachable from the Sandbox. It may be the service root or `/agent-stub`. Enables `DIFY_AGENT_STUB_*` env injection for user `shell.run` jobs. |
| `DIFY_AGENT_SANDBOX_FILES_BASE_URL` | empty | Dify API base URL reachable from the Sandbox for signed `/files/*` upload/download bytes, including Config file and skill pulls. Required when Agent Stub file operations are enabled. May include an ingress path prefix, but not a query or fragment. |
+| `DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT` | `50` | Agent service-owned maximum Agent Stub upload size in MiB. The file-request handler factory converts it to bytes and sends it to Dify API as the required `max_size` used to sign a size-limited upload URL. |
| `DIFY_AGENT_SERVER_SECRET_KEY` | empty | Security-sensitive server-wide root secret used to derive the JWE encryption key for Agent Stub bearer tokens; required when `DIFY_AGENT_STUB_API_BASE_URL` is set. The supplied default config uses a development value; set a unique unpadded base64url 32-byte secret in production. |
| `DIFY_AGENT_OUTBOUND_HTTP_CONNECT_TIMEOUT` | `10` | Shared outbound HTTP connect timeout in seconds. |
| `DIFY_AGENT_OUTBOUND_HTTP_READ_TIMEOUT` | `600` | Shared outbound HTTP read timeout in seconds. |
@@ -89,6 +90,7 @@ DIFY_AGENT_LOCAL_SANDBOX_WORKSPACE_ROOT=/tmp/dify-agent/workspaces
DIFY_AGENT_LOCAL_SANDBOX_HOME_SNAPSHOT_ROOT=/tmp/dify-agent/home-snapshots
DIFY_AGENT_STUB_API_BASE_URL=https://agent.example.com/agent-stub
DIFY_AGENT_SANDBOX_FILES_BASE_URL=https://dify.example.com
+DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT=50
# This is security-sensitive: it derives the JWE encryption key for Agent Stub bearer tokens.
# Replace this development default in production.
# Generate one with: python -c 'import secrets; print(secrets.token_urlsafe(32))'
@@ -110,10 +112,11 @@ Removing Agent Stub gRPC is a breaking transport migration: replace every
For a remote Sandbox, expose only `/agent-stub/*` from Agent Backend and the
existing `/files/*` Dify API data plane. The `/files/*` ingress must preserve
-the complete signed query string, allow the configured upload body size, and
-use response streaming and timeouts suitable for large downloads. Do not expose
-Agent Backend `/runs`, Workspace, or Binding management routes through the
-Sandbox ingress.
+the complete signed query string and set its request-body limit above the
+configured file-size limit to leave room for multipart framing and headers; the
+two limits need not be numerically equal. Use response streaming and timeouts
+suitable for large downloads. Do not expose Agent Backend `/runs`, Workspace,
+or Binding management routes through the Sandbox ingress.
Browser presentation URLs are independent. Configure Dify API `FILES_URL` to a
browser-reachable public origin, or leave it empty so responses use same-origin
diff --git a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
index 97155355f62..9520b6e29cd 100644
--- a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
+++ b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
@@ -93,6 +93,7 @@ topology.
```env
DIFY_AGENT_STUB_API_BASE_URL=https://agent.example.com/agent-stub
DIFY_AGENT_SANDBOX_FILES_BASE_URL=https://dify.example.com
+DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT=50
DIFY_AGENT_SERVER_SECRET_KEY=replace-with-unpadded-base64url-for-32-random-bytes
```
@@ -100,6 +101,11 @@ HTTP URLs may be either the service root or the explicit `/agent-stub` root.
The server normalizes a service root and rejects unrelated paths. The separate
Sandbox file base must point to the Dify API ingress serving `/files/*`; it is
used for CLI upload/download bytes, including Config file and skill pulls.
+`DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT` belongs to the Agent service, is in
+MiB, and defaults to `50`. The Agent service converts it to the signed upload
+URL's byte limit. Any ingress or proxy in front of `/files/*` must allow that
+file limit plus multipart framing and header overhead; its request-body limit
+does not need to be numerically identical.
After `dify-agent file upload <path>` succeeds, the CLI prints JSON such as:
diff --git a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py
index 636a88247d1..ff7c409b8c2 100644
--- a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py
+++ b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py
@@ -103,7 +103,8 @@ class DifyApiAgentStubFileRequestHandler:
The upload path calls ``/inner/api/agent/files/upload-request`` and injects the
authenticated execution context's ``tenant_id``, ``user_id``, ``user_from``, and optional
- ``conversation_id`` along with the requested filename and mimetype. The download path calls
+ ``conversation_id`` along with the requested filename, mimetype, and configured upload-size
+ limit. The download path calls
``/inner/api/agent/files/download-request`` and injects ``tenant_id``,
``user_id``, ``user_from``, and ``invoke_from`` plus the validated public
file mapping.
@@ -119,6 +120,7 @@ class DifyApiAgentStubFileRequestHandler:
inner_api_url: str
inner_api_key: str
sandbox_files_base_url: str
+ max_upload_size_bytes: int
timeout: httpx.Timeout | float = 30.0
async def create_upload_request(
@@ -147,6 +149,7 @@ class DifyApiAgentStubFileRequestHandler:
"filename": request.filename,
"mimetype": request.mimetype,
"conversation_id": execution_context.conversation_id,
+ "max_size": self.max_upload_size_bytes,
}
data = await self._post_inner_api("/inner/api/agent/files/upload-request", payload)
upload_uri = data.get("upload_uri")
diff --git a/dify-agent/src/dify_agent/server/settings.py b/dify-agent/src/dify_agent/server/settings.py
index d46cc29a31f..197592c8815 100644
--- a/dify-agent/src/dify_agent/server/settings.py
+++ b/dify-agent/src/dify_agent/server/settings.py
@@ -77,6 +77,12 @@ class ServerSettings(BaseSettings):
default=None,
validation_alias="DIFY_AGENT_SANDBOX_FILES_BASE_URL",
)
+ stub_upload_file_size_limit: int = Field(
+ default=50,
+ ge=0,
+ description="Maximum Agent Stub upload size in MiB",
+ validation_alias="DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT",
+ )
server_secret_key: str | None = None
api_token: str | None = None
shell_redact_patterns: str = ""
@@ -222,6 +228,7 @@ class ServerSettings(BaseSettings):
inner_api_url=self.inner_api_url,
inner_api_key=self.inner_api_key,
sandbox_files_base_url=self.sandbox_files_base_url,
+ max_upload_size_bytes=self.stub_upload_file_size_limit * 1024 * 1024,
timeout=self.create_outbound_http_timeout(),
)
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py b/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py
index 8a99158b20f..d49a66e44ef 100644
--- a/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py
+++ b/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py
@@ -15,6 +15,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubConfigDownloadSource,
AgentStubFileDownloadRequest,
AgentStubFileMapping,
+ AgentStubFileUploadRequest,
agent_stub_connections_url,
agent_stub_drive_base_for_ref,
agent_stub_drive_commit_url,
@@ -54,6 +55,13 @@ def test_agent_stub_file_request_urls_handle_trailing_slash() -> None:
)
+def test_agent_stub_file_upload_request_rejects_client_max_size() -> None:
+ with pytest.raises(ValidationError, match="extra_forbidden"):
+ AgentStubFileUploadRequest.model_validate(
+ {"filename": "report.pdf", "mimetype": "application/pdf", "max_size": 1024}
+ )
+
+
def test_agent_stub_drive_request_urls_handle_trailing_slash() -> None:
assert agent_stub_drive_manifest_url("https://agent.example.com/agent-stub/") == (
"https://agent.example.com/agent-stub/drive/manifest"
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py
index 2f204ac2b71..13e8f34089f 100644
--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py
+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py
@@ -47,6 +47,7 @@ def _file_handler(*, sandbox_files_base_url: str = "https://sandbox-files.exampl
inner_api_url="https://api.internal.example.com",
inner_api_key="inner-secret",
sandbox_files_base_url=sandbox_files_base_url,
+ max_upload_size_bytes=50 * 1024 * 1024,
)
@@ -66,6 +67,7 @@ def test_upload_request_uses_agent_inner_endpoint_and_binds_sandbox_base(monkeyp
"filename": "report.pdf",
"mimetype": "application/pdf",
"conversation_id": "conversation-1",
+ "max_size": 50 * 1024 * 1024,
}
return httpx.Response(200, json={"upload_uri": "/files/upload/for-plugin?signed=yes"})
diff --git a/dify-agent/tests/local/dify_agent/server/test_settings.py b/dify-agent/tests/local/dify_agent/server/test_settings.py
index b4190c29082..29908851d85 100644
--- a/dify-agent/tests/local/dify_agent/server/test_settings.py
+++ b/dify-agent/tests/local/dify_agent/server/test_settings.py
@@ -97,12 +97,31 @@ def test_server_settings_defaults_shellctl_auth_token_to_none(
def test_server_settings_reads_agent_stub_settings_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub/")
monkeypatch.setenv("DIFY_AGENT_SANDBOX_FILES_BASE_URL", "https://dify.example.com/prefix/")
+ monkeypatch.setenv("DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT", "72")
monkeypatch.setenv("DIFY_AGENT_SERVER_SECRET_KEY", _base64url_secret(secrets.token_bytes(32)))
settings = ServerSettings()
assert settings.agent_stub_api_base_url == "https://agent.example.com/agent-stub"
assert settings.sandbox_files_base_url == "https://dify.example.com/prefix"
+ assert settings.stub_upload_file_size_limit == 72
+
+
+def test_server_settings_defaults_stub_upload_file_size_limit_to_50_mib(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.delenv("DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT", raising=False)
+ monkeypatch.chdir(tmp_path)
+
+ assert ServerSettings().stub_upload_file_size_limit == 50
+
+
+def test_server_settings_accepts_zero_and_rejects_negative_stub_upload_file_size_limit() -> None:
+ assert ServerSettings(stub_upload_file_size_limit=0).stub_upload_file_size_limit == 0
+
+ with pytest.raises(ValidationError):
+ _ = ServerSettings(stub_upload_file_size_limit=-1)
def test_server_settings_normalizes_agent_stub_service_root_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -240,6 +259,7 @@ def test_server_settings_create_agent_stub_file_request_handler_returns_handler_
inner_api_url="https://api.example.com",
inner_api_key="inner-secret",
sandbox_files_base_url="https://sandbox-files.example.com/dify",
+ stub_upload_file_size_limit=72,
)
handler = settings.create_agent_stub_file_request_handler()
@@ -248,6 +268,7 @@ def test_server_settings_create_agent_stub_file_request_handler_returns_handler_
assert handler.inner_api_url == "https://api.example.com"
assert handler.inner_api_key == "inner-secret"
assert handler.sandbox_files_base_url == "https://sandbox-files.example.com/dify"
+ assert handler.max_upload_size_bytes == 72 * 1024 * 1024
def test_server_settings_create_agent_stub_drive_request_handler_returns_none_without_full_settings() -> None:
diff --git a/docker/envs/core-services/dify-agent.env.example b/docker/envs/core-services/dify-agent.env.example
index a3e61fbed6f..44d5f4ebb0f 100644
--- a/docker/envs/core-services/dify-agent.env.example
+++ b/docker/envs/core-services/dify-agent.env.example
@@ -35,6 +35,8 @@ DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS=3600
DIFY_AGENT_E2B_SHELLCTL_PORT=5004
# Sandbox-reachable Dify API base for signed /files/* transfers.
DIFY_AGENT_SANDBOX_FILES_BASE_URL=http://api:5001
+# Maximum Agent Stub upload size in MiB; forwarded to Dify API as a signed byte limit.
+DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT=50
DIFY_AGENT_STUB_API_BASE_URL=http://agent_backend:5050/agent-stub
# This is security-sensitive: it derives the JWE encryption key for Agent Stub bearer tokens.
# Replace this development default in production.