Why Giving an AI Browser MCP Unrestricted File Upload Leaks Your Cookies — And How We Built Fail-Closed Native Uploads in Rust
How prompt-injected pages can exfiltrate storageState cookies through misconfigured browser MCP uploads, and how sessfork-mcp enforces native CDP DOM.setFileInputFiles, fail-closed --upload-root allowlists, unconditional credential denylists, and an empty-by-default upload-staging workflow.
🌐 阅读中文版本 →On this page
- 1. Three Real Risks in Browser MCP File Uploads
- 2. Protocol Choice: Native CDP DOM.setFileInputFiles vs. JS DataTransfer
- 3. Four Fail-Closed Guardrails in sessfork-mcp
- 4. Two Real P1 Bugs Caught by Independent Diff Review
- 5. Operational Pattern: The Empty-by-Default upload-staging/ Outbox
- 6. Verification & Links
When an AI agent fills out web forms on your behalf—attaching PDFs, screenshots, or build archives—the naive solution is adding a file_upload tool that accepts any local path.
Without strict isolation, that single tool turns into a silent credential-exfiltration vector.
In sessfork-mcp (our pure-Rust, zero-Node.js, zero-Tokio CDP MCP server; commit 7543c1e), we just shipped native browser_file_upload (bringing the exposed toolset to 19 tools). Here is a breakdown of the three real failure modes in browser MCP file uploads, why we chose native CDP DOM.setFileInputFiles over JS DataTransfer, and two subtle P1 bugs caught by an independent diff review before shipping.
1. Three Real Risks in Browser MCP File Uploads
- Session state and upload roots sharing the same directory
If a browser MCP server stores exported cookies or
localStoragetokens inside--output-dirand allows uploads from that same root—or runs with--allow-unrestricted-file-access—a single prompt-injected webpage can instruct the agent to attachstorageStateJSON straight into an attacker-controlled upload form. - Eager pre-upload leaks across tasks
Even when an allowlist exists, pointing it at a broad historical folder means a multi-task agent can attach the wrong draft or archive. Many modern web forms upload files immediately on file-input
changeevents, long before a human clicks the finalSubmitbutton. - Path-existence oracles and directory leaks Returning distinct errors for “file not found” vs. “outside allowed directory” lets an untrusted prompt probe the host filesystem. Echoing absolute paths back in tool receipts leaks local usernames and project layout into LLM context.
2. Protocol Choice: Native CDP DOM.setFileInputFiles vs. JS DataTransfer
sessfork-mcp speaks standard CDP over OS pipes (--remote-debugging-pipe with lexmount/moli) or loopback WebSockets (--cdp-url with Chrome/Chromium). We benchmarked two upload mechanisms against a live local FormData endpoint:
| Dimension | JS Runtime.callFunctionOn + DataTransfer |
Native CDP DOM.setFileInputFiles |
|---|---|---|
| Memory overhead | Reads file into Rust, base64-encodes over JSON-RPC, decodes into V8 heap | Zero base64 bloat; passes canonical path after validation so the browser reads natively |
| Event fidelity | Synthetic dispatchEvent(new Event('change')) produces isTrusted: false |
Fires native isTrusted: true input and change events |
| Large archives / video | Bounded by JSON-RPC payload size & atob allocation |
Handles large files up to configurable --max-upload-mb |
| MIME & reset semantics | Requires manual extension-to-MIME table | Kernel infers MIME (image/png, application/zip, etc.); paths: [] clears cleanly |
Testing directly against moli 1.1.27 confirmed full native support for DOM.setFileInputFiles (via both objectId and backendNodeId), exact binary FormData delivery, and Chromium-compatible UnableToSetFileInput errors when targeting non-file elements or sending multiple files to a single-file input.
3. Four Fail-Closed Guardrails in sessfork-mcp
All validation runs upfront before spawning or attaching to a browser process:
browser_file_upload(ref|selector, paths)
│
├─► 1. Disabled by default: upload_roots empty? ──yes──► Reject immediately
├─► 2. Input shape: non-array / >20 files / empty / NUL? ──yes──► Reject
├─► 3. Canonicalize + single metadata() check
│ (non-file / missing / outside return identical opaque error)
├─► 4. Unconditional credential denylist (evaluated BEFORE allowlist):
│ .sessfork (case-insensitive on Win/macOS) / --output-dir / --storage-state? ──yes──► Reject
└─► 5. Narrow --upload-root + configurable --max-upload-mb (default 100 MiB, 1..10240)
──► Strip Windows \\?\ verbatim prefix ──► CDP DOM.setFileInputFiles
──► Action Receipt prints basenames only (e.g. shot.png, poc.zip)
Key design details in storage.rs and browser.rs:
- Denylist before allowlist: Even if an operator configures an overly broad
--upload-root, any path containing.sessfork, inside--output-dir, or matching--storage-stateis unconditionally blocked. - No size oracle on external files: File size (
meta.len() > max_upload_bytes) is checked only after the file is proven to live inside an allowed--upload-rootand outside all forbidden paths. - User-configurable size cap (
--max-upload-mb): Defaults to100MiB and accepts1..=10240MiB (up to 10 GiB) acrosssessfork-mcp,sessfork-mcp setup, and Python’smcp_setup.py. Passing0directly inBrowserConfigfails closed. - Basename-only receipts:
Action Receiptlogs onlycanon.file_name(), keeping local filesystem paths out of model context.
4. Two Real P1 Bugs Caught by Independent Diff Review
Before committing, we ran an independent adversarial review over the raw git diff (without sharing author assumptions). It caught two subtle cross-platform P1 bugs that unit tests on macOS alone had missed:
- Windows
\\?\verbatim prefix breaking CDP consumers On Windows,fs::canonicalize()prepends\\?\(or\\?\UNC\). Passing that raw verbatim string straight intoDOM.setFileInputFilesbreaks Chromium/Electron path consumers. We reusedstrip_windows_verbatim_prefixright after canonicalized security checks and right before the CDP call. - Python
Sequenceaccepting a barestrand whitespace resolving tocwd()Inbuild_managed_moli_mcp_entry(..., upload_roots: Optional[Sequence[Path]] = None), PythonstrandbytesimplementSequence. Passingupload_roots="/tmp/docs"would iterate character-by-character and emit--upload-root=/(exposing/). Worse, passing""or" "would causePath(root).expanduser().resolve()to resolve toPath.cwd(). We added explicitisinstance(upload_roots, (str, bytes, os.PathLike))rejection plus.strip()and NUL-byte checks with matching negative-control tests.
5. Operational Pattern: The Empty-by-Default upload-staging/ Outbox
Code guardrails pair best with a simple operational habit: instead of pointing --upload-root at a permanent archive directory, point it at a 0700 upload-staging/ directory that stays empty at rest.
- At rest,
upload-staging/contains zero files—a prompt-injected page has nothing to exfiltrate. - Whenever a workflow needs to attach files, an automation step clears
upload-staging/, copies only the current task’s approved files in, runsbrowser_file_upload, verifies the UI attachment list, and wipesupload-staging/immediately afterward.
6. Verification & Links
-
Rust CI (Ubuntu, macOS, Windows):
cargo fmt --check,cargo clippy --locked --all-targets -- -D warnings(0 warnings),cargo test --locked --no-fail-fast(48 passed). -
Python suite:
PYTHONPATH=src python3 -m unittest discover -s tests(52 passed). -
Live E2E probe (
sessfork-mcp+moli 1.1.27): Verified real binary PNG + ZIPFormDataupload,isTrusted: trueevents,paths: []reset, and fail-closed rejection on outside paths,.sessfork/state.json, non-file buttons (UnableToSetFileInput), and unconfigured instances. -
GitHub (MIT): https://github.com/wasabihu/sessfork
-
Standalone Rust MCP Docs: https://github.com/wasabihu/sessfork/tree/main/rust/sessfork-mcp
More Articles (18)
- EN When a Headless Browser Burns 6 Cores: Debugging a 567% V8 GC Spin and Building a Zero-Tokio MCP Idle Reaper
- 中文 当无头浏览器烧满 6 核 CPU:从 567% V8 GC 死循环到零 Tokio Rust MCP 空闲回收
- 中文 为什么别给 AI 浏览器 MCP 开全盘文件上传:原生 CDP 零拷贝与 4 道 Fail-Closed 防线
- 中文 拆完 14.5K★ GenericAgent 源码后,我把它的 3 个浏览器实战绝招安全搬进了 913 KB 纯 Rust MCP(17/17 对抗测试全绿)
- EN Zero-Dependency Engineering: Adding BibTeX/LaTeX, Git-Diff Gating, SARIF, and Security Confinement to claimcite Without Losing a Millisecond
- 中文 零依赖工程实践:如何在 56ms 冷启动与 0 第三方库约束下,给 claimcite 加上 LaTeX、Git 增量门禁与防注入安全围栏
- 中文 零依赖、可复现地抓出 AI 引文幻觉:从 4 类隐蔽学术造假到本地 xerj:// 字节跨度核验
- EN Catching Silent AI Citation Hallucinations With Zero-Dependency Deterministic Verification
- EN Hardening an AI Browser MCP Without Stripping CSP: Origin-Guarded Iframes, Fail-Fast Batching & 17 Adversarial Probes
- 中文 AI 浏览器 8 步烧掉 174K Token?我把零布局 AXTree 蒸馏塞进 848 KB 纯 Rust MCP,Token 直降 85.4%
- 中文 我用 Rust + Python 拼了一套完全本地、零云端、可逐字验真的 AI Agent 知识库闭环(开源)
- 中文 24 GB 笔记本零 Swap 并发 160 个 AI 浏览器:换纯 Rust MCP 连 Chrome 也省 503 MB
- EN Cutting AI Browser MCP Tokens by 85.4% (174K -> 25K) & Running 160 Parallel Agents with an 848 KB Zero-Tokio Rust Server
- EN Why Qwen3-Reranker-0.6B Hits Only 20.8% Strict Calibration on Financial Traps — And How We Built a Clean-Room 98.3% Fix + 5.4ms ONNX Drop-In
- 中文 砍掉 Node @playwright/mcp 换 605 KB 纯 Rust 管道:Moli 提速 6×、内存降 90.7%(官方 M4 复现)
- 中文 给 19.4k★ Rust AI 搜索引擎 XERJ 做中文 RAG 评测:不改底层代码,如何把 R@3 从 22.2% 拉到 91.1%
- EN Stop AI Agents From Hijacking Your Chrome Window: Fork Live Sessions into Headless Playwright MCP
- 中文 受够 AI 浏览器抢焦点:开源了纯 Python 零依赖工具 sessfork,一键将 Chrome 登录态分叉到无头 Playwright MCP