Dosu LogoDosu Logo
Ask
Join our Discord
Organization avatar
difyPublic
Dify
Documentsdify
File Upload and Download Integrity
File Upload and Download Integrity
Type
Topic
Status
Published
Created
Aug 5, 2026
Updated
Aug 6, 2026
Created by
Dosu Bot
Updated by
Dosu Bot

File Upload and Download Integrity#

Two distinct integrity risks exist in Dify's file pipeline:

  1. Upload — silent stream truncation: Most upload controllers call file.stream.read() without first calling file.stream.seek(0). If any middleware or validation code has advanced the stream position, the read silently returns a partial payload; no error is raised and the truncated bytes are committed to storage with an equally-truncated size recorded in the DB.

  2. Download — Content-Length / actual-size mismatch: Download responses set the Content-Length header from the UploadFile.size database column with no verification against the bytes actually stored in the backend. A bug in upload_text previously stored character count (len(text)) rather than byte count, poisoning the DB value for non-ASCII uploads; this was fixed in PR #40034, though historical records may still contain incorrect metadata.


Upload: Silent Stream Truncation#

Pattern#

The plugin upload endpoint reads the stream directly without first seeking to position 0 :

file_binary=file.stream.read(),

The same unseek'd file.stream.read() pattern appears in at least six other controllers:

  • api/controllers/service_api/app/file.py
  • api/controllers/console/files.py
  • api/controllers/web/files.py
  • api/controllers/openapi/files.py
  • api/controllers/service_api/dataset/document.py

Because read() returns bytes from the current stream position, any upstream code that advances the cursor produces a silently-truncated payload. The downstream storage call succeeds, and len(file_binary) records the truncated size as ground truth in UploadFile.size — with no exception, no log warning.

Downstream path#

FileService.upload_file computes size as file_size = len(content) where content is the bytes already read from the stream. ToolFileManager.create_file_by_raw does the same (size=len(file_binary)). Both methods faithfully record whatever bytes they received — the corruption is silent and upstream.

Safer counter-pattern#

AnnotationBatchImportApi is the only controller with explicit stream position management :

file.stream.seek(0, 2) # seek to end to determine size
file_size = file.stream.tell()
file.stream.seek(0) # reset to beginning before reading

All other upload controllers should follow this pattern.

PR context#

PR #35985 standardized all controllers from file.read() to file.stream.read() across the console, service-api, web, and openapi namespaces, but did not add seek(0) guards. The vulnerability pattern is now uniformly present across the codebase.


Download: Content-Length Mismatch#

Header sourced from DB metadata#

FilePreviewApi.get sets the response header unconditionally from the database column:

if upload_file.size > 0:
    response.headers["Content-Length"] = str(upload_file.size)

upload_file.size is the value persisted at upload time — never re-validated against the storage backend. If the stored file has changed size (storage corruption, manual intervention, or silent truncation from an upload bug), the header is wrong. Clients relying on Content-Length for range requests, progress bars, or integrity checks receive incorrect data.

upload_text recorded characters, not bytes (fixed in PR #40034)#

FileService.upload_text previously saved text.encode("utf-8") to storage but recorded size=len(text) — the Unicode character count, not the UTF-8 byte length. For any text containing multi-byte characters (CJK, emoji, accented Latin), the DB size was smaller than the actual stored file. Content-Length would be under-reported on downloads, causing clients to treat the transfer as complete before all bytes were received.

PR #40034 fixed this by encoding the text once, saving those bytes, and using len(content) for the size — consistent with FileService.upload_file, which already used file_size = len(content) where content is bytes.

Note: Historical UploadFile records created before this fix may still have incorrect size metadata for non-ASCII text. The upload process itself now correctly stores UTF-8 byte lengths.


Affected Endpoints Summary#

EndpointFileRisk
POST /files/upload/for-pluginupload.py:101-109Upload truncation
POST /files/upload (console / service-api / web / openapi)multiple controllersUpload truncation
GET /<file_id>/file-previewimage_preview.py:95-144Content-Length from unverified DB value
Text files uploaded via upload_textfile_service.py:167-198FIXED in PR #40034: DB size = character count, not bytes

Key Source Locations#

FilePurpose
api/controllers/files/upload.pyPlugin upload endpoint — unseek'd stream read
api/services/file_service.pyCore upload service; upload_text encodes once & uses len(content) for byte size (fixed in PR #40034)
api/controllers/files/image_preview.pyDownload/preview controller; Content-Length from DB
api/controllers/console/app/annotation.pyReference: correct seek-before-read pattern
api/core/tools/tool_file_manager.pycreate_file_by_raw — size from truncated bytes
PR #35985Standardized file.stream.read() without adding seek guards
Documents
Account Activity Tracking
Agent API Routes
Agent App Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent App Event Architecture
Agent Cost and Usage Tracking
Agent File Handling
Agent File Upload Configuration
Agent Icon Data Model
Agent Log Event Pipeline
Agent Message History
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Model Settings
Agent Node Data Models
Agent Response Schema
Agent Runtime
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Runtime Backend Initialization
Agent Runtime Layer Provider Registration
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Sandbox SSRF Allowlisting
Agent Shell Layer
Agent Strategy Plugin Architecture
Agent V2 Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent V2 Configure Interface
Agent V2 Feature Flags
Agent V2 File and Vision Handling
Agent V2 Variable System
App Mode Configuration
App Publishing and Embedding
Audio to Text API
Auth Route Architecture
Automatic Rule Generation
Avatar Management
Branding Customization
Browser Tab and State Management
Builtin Tool Provider Credentials
Celery Task Resilience
Chat Avatar Rendering
Chatbot Conversation State Recovery
Chatbot Widget Embedding
Code Node Execution
Code Node Output Validation
Collaborative Workflow Editing
Conversation Auto-Naming
Credential Encryption and Secret Management
Custom Tool Authentication
Custom Tool HTTP Timeout Configuration
Custom Tool OpenAPI Integration
Data Export
Database Migration System
Database Session Management
Database Transaction Isolation
Dataset Batch Import
Dataset Deletion
Dataset Permission Model
Dataset Segmentation Configuration
Dependency Injection and Testability
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Agent Monorepo Structure
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Cloud Billing
Dify OpenAPI
difyctl CLI
Docker Container Security
Docker Deployment and Upgrades
Docker Frontend Configuration
Docker Image Publishing
Docker Networking
Document Indexing Operations
Edition-Based Feature Gating
Elasticsearch Integration
External Knowledge Integration
File Access Control
File Array Handling
File Download Architecture
File Download Security
File Storage Synchronization
File Upload and Download Integrity
File Upload Configuration
File Upload Processing
File URL Resolution
Flask Application Architecture
Flask Blueprint and Route Registration
Graph Streaming Infrastructure
Home Directory Management
HTTP Request Node
HTTP Request Node Key-Value Editor
HTTP Request Node Size Constraints
httpx and Gevent Compatibility
Human Input Node
Hybrid Search
Icon URL Resolution
Iframe Embedding Security
Jina Reranker Integration
JWT Authentication
Knowledge Base API
Knowledge Base Document Processing
Knowledge Base Metadata Filtering
Knowledge Base Summarization Pipeline
Langfuse Integration
Lexical Editor Integration
LLM Provider Message Validation
LLM Structured Output
Local Development Configuration
Log Filtering
Markdown Rendering
MCP Client Transport and Connectivity
MCP Protocol Integration for Dify Workflows
MCP OAuth Integration
MCP Protocol Integration
Dify Agent Server 模块分析 (Commit 55f95dbc)
MCP Protocol Integration for Dify Workflows
MCP Provider Architecture
MCP Tool Integration
MCP Protocol Integration for Dify Workflows
MCP Tool Parameter Binding
Messaging Platform Integration
Milvus Integration
Model Provider Error Handling
Monaco Editor Integration
Multi-Tenant Context Propagation
Multimodal Knowledge Base Support
Next.js Routing and Redirects
Next.js SSR Authentication
Nginx Reverse Proxy Configuration
OAuth Login Flow
Observability and Tracing
OpenAI-Compatible Server Integration
OpenDAL Storage Backend
Ops Trace Data Models
Parallel Workflow Execution
Parent-Child Retrieval Architecture
Plugin API Key Configuration
Plugin Architecture
Plugin Credential Management
Plugin Daemon Architecture
Plugin Daemon Communication
Plugin Daemon Model Parameter Handling
Plugin Daemon Port Configuration
Plugin Database Integrity
Plugin Error Handling
Plugin Lifecycle Management
Plugin Model Caching
Plugin Permissions
Plugin Storage Configuration
Plugin System Timeouts
Plugin Taxonomy and Validation
Plugin Trigger OAuth Refresh
PNPM Monorepo Dependency Management
PostgreSQL Generated Columns
Provider Model & Credential Management
Pyrefly Type Checker
Rate Limiting and Concurrency Control
RBAC Initialization
Reasoning Tag Filtering
Redis Connection Management
Redis Streaming Resilience
Release Breaking Changes
Remote File Handling and Validation
Retrieval Filtering and Scoring
RTL Locale Support
Sandbox Code Execution
Sandbox Network Isolation
Sandbox Seccomp Security
Segment Update and Attachment Lifecycle
Server Deployment Configuration
Service API Pagination
Shell Provider Lifecycle
Snippet Variable Handling
SQLite Test Infrastructure
SSE Stream Lifecycle
SSE Stream Terminal Event Delivery
SSL/TLS Certificate Management
SSR Data Fetching
SSRF Proxy
Suggested Questions After Answer
Summary Index
Tenant-Isolated Document Indexing Queue
Test Doubles and In-Memory Repositories
Dify Agent Server 模块分析 (Commit 55f95dbc)
TiDB Vector Full-Text Search
Timestamp Management
Tool File URL Signing
Tool Node Input Validation
Tool Provider Authorization
Trace Task Pipeline
TTS Audio Playback
User and Tenant Context Propagation
User Roles and Permissions
Variable Pool Falsy Value Handling
Variable Resolution and Template Substitution
Vector Database Plugin Architecture
Vector Store Integration
Vite Configuration
Weaviate Vector Store
Web Container Docker Configuration
Webhook Trigger System
WebSocket Service Architecture
Word Document Extraction
Workflow Agent Node Configuration
Workflow Agent Retry Configuration
Workflow and Agent Composition
Workflow Conditional Branching
Workflow Container Nodes
Workflow Conversation State Management
Workflow Draft Synchronization
Workflow Execution Dispatch
Workflow Execution Persistence
Workflow Fail Branch Architecture
Workflow File Handling
Workflow Iteration Node Execution
Workflow LLM Node Configuration
Workflow Memory Management
Dify Agent Server 模块分析 (Commit 55f95dbc)
Workflow Node Canvas Summary Rendering
Workflow Node Versioning
Workflow Pause-Resume State Management
Workflow Resume Architecture
Workflow Run State Management
Workflow Schedule Triggers
Workflow Test Run Execution
Workflow Timeout and Execution Limits
Workflow Variable Size Management