From One False-Positive SAST SQL Alert to Six Real P1 Fixes: A Full White-Box Security Audit of sessfork
An automated scanner flagged a static SQLite column toggle in sessfork as SQL injection. Confirming it was a 100% false positive triggered a full-stack white-box audit across the Rust CDP MCP server, Python CLI, Chrome extension, and Windows installer—uncovering six real P1 flaws beneath a green 29/29 security suite.
🌐 阅读中文版本 →On this page
- 1. Why a Green 29/29 Adversarial Suite Still Missed Real Bugs
- 2. The Six Confirmed P1 Fixes
- P1-1: Hot-Reload localStorage Navigation TOCTOU & Silent Main-World Fallback
- P1-2: browser_evaluate Missing Runtime expectedOrigin Lock Inside Child Frames
- P1-3: Fail-Open Python load_storage_state Silently Wiping state.json on Corruption
- P1-4: Extension Session TTL Silently Expiring Only While Popup Remains Open
- P1-5: Unredacted Query Secrets & Token Prefixes in Extension IDOR Reports
- P1-6: Supply-Chain Asymmetry in install.ps1
- 3. Five P2 Defense-in-Depth Hardening Improvements
- 4. Verification Results & Honest Boundaries (Not tested ≠ clean)
- 5. Five Audit Habits Worth Keeping for Any Credential-Handling Agent Tool
It started with a noisy static analysis (SAST) alert: an automated scanner spotted an f-string inside a SQLite SELECT query in chrome.py and labeled it a SQL injection hazard.
Opening the function immediately proved it was a 100% static-literal false positive. The code copies Chrome’s Cookies file using O_NOFOLLOW into a 0600 snapshot inside a 0700 temporary directory, checks PRAGMA table_info(cookies) for legacy schema compatibility, and interpolates exactly one of two compile-time constants:
top_frame_col = "top_frame_site_key" if "top_frame_site_key" in columns else "''"
cur.execute(
f"""
SELECT host_key, name, value, encrypted_value, path,
expires_utc, is_secure, is_httponly, has_expires, samesite,
{top_frame_col}
FROM cookies
"""
)
No untrusted input can ever touch top_frame_col. Splitting that query into two static constant SQL strings cleanly silences the scanner noise.
What bothered us was the follow-up question: sessfork already ships with a live adversarial verification harness (scripts/security_verify.py passing 29/29), 67 Python unit tests, and 73 Rust unit tests. If we had simply dismissed the SAST alert and moved on, what real cross-boundary bugs were hiding underneath a green test suite?
So we ran a full-stack white-box audit across all four trust layers—Python session extraction, Chrome MV3 extension, Rust CDP MCP server + native host, and release installers—filtering every candidate through a strict 7-question false-positive triage gate. Underneath the green checks, we found and fixed six concrete P1 boundary flaws.
1. Why a Green 29/29 Adversarial Suite Still Missed Real Bugs
Automated security probes tend to test the invariants you already thought to defend. What usually breaks in production are cross-layer mismatches and execution-window races between components:
- Out-of-scope threats stay explicitly documented, not inflated: Same-UID local malware or intentionally reading same-origin non-
HttpOnlystate viabrowser_evaluateare already documented as non-goals inSECURITY.md. Every reported issue had to break an active security boundary. - Audit the seams, not just individual modules:
- OS extraction & state persistence (
chrome.py,crypto.py,localstorage.py,state.py) - Browser extension ↔ native messaging host (
popup.js,idor_engine.js↔native_host.rs,api_server.rs,handoff.rs) - CDP isolated worlds & frame locking (
browser.rs,storage.rs,ws_cdp.rs) - Installers & release supply chain (
install.sh,install.ps1,Cargo.lock, GitHub Actions)
- OS extraction & state persistence (
2. The Six Confirmed P1 Fixes
P1-1: Hot-Reload localStorage Navigation TOCTOU & Silent Main-World Fallback
During browser_set_storage_state or browser_handoff(complete), apply_storage_state_to_context queried Page.getFrameTree to learn top_frame.origin, generated a single-origin script holding only that origin’s localStorage items, and evaluated it via eval_in_isolated_world.
Two weaknesses combined into a cross-origin token leak risk:
- No runtime
location.origincheck inside the injected JS: Because a top-level tab reuses the same CDPframeIdacross navigations, a fast redirect to another origin betweenPage.getFrameTreeandRuntime.evaluatewould write Site A’slocalStoragetokens straight into Site B’swindow.localStorage. - Silent fallback to main-world
Runtime.evaluate: Unliketool_evaluate(which fails closed),eval_in_isolated_worldfell back to main-world evaluation ifPage.createIsolatedWorldfailed or omittedexecutionContextId—exposing injected entries to tamperedStorage.prototypesetters on hostile pages.
The fix:
- Keep
eval_in_isolated_worldstrictly for non-secret DOM metadata (document.title,readyState, Markdown extraction), and introduceeval_in_isolated_world_strict(rust/sessfork-mcp/src/browser.rs) forlocalStoragehydration and live handoff extraction—failing closed if an isolated world cannot be created. - Inject an origin lock at the top of
build_single_origin_local_storage_sync_script(rust/sessfork-mcp/src/storage.rs) beforelocalStorage.clear()/localStorage.setItem(), and strip redundant:80/:443default ports innormalize_origin:
const __expected = "https://app.example.com";
if (!__expected || location.origin.toLowerCase() !== __expected) return;
P1-2: browser_evaluate Missing Runtime expectedOrigin Lock Inside Child Frames
To guard cross-origin iframes, browser_evaluate requires both allowCrossOrigin: true and an explicit expectedOrigin matching the frame tree. Previously, after authorize_frame_evaluate checked the frame tree snapshot, the injected guarded_expr only verified window.origin === 'null' (blocking opaque sandboxed frames)—it did not re-check location.origin.toLowerCase() inside the isolated world right before evaluation.
Our earlier D9 probe tested stale removed frameIds, missing the case where an iframe navigates cross-origin while keeping the same frameId.
The fix: Added build_guarded_frame_eval_expression (rust/sessfork-mcp/src/browser.rs) to enforce both non-opaque origins and exact location.origin.toLowerCase() === __exp inside the execution world for child frames (and top frames whenever expectedOrigin is specified).
P1-3: Fail-Open Python load_storage_state Silently Wiping state.json on Corruption
We caught an asymmetric fail-open bug between the Rust and Python layers:
- Rust’s
load_existing_state_strictrefuses to overwrite a corrupted or malformedstate.json(explicitly covered insecurity_verify.py); - Python’s
load_storage_stateinsrc/sessfork/state.pycaught(OSError, json.JSONDecodeError)and quietly returned{"cookies": [], "origins": []}.
As a result, running an incremental single-domain sync or sessfork --clear example.com while state.json was truncated or malformed would treat the vault as empty and overwrite every other saved domain’s sessions.
The fix (src/sessfork/state.py):
- Added
_read_regular_file_nofollowusingos.O_RDONLY | os.O_NOFOLLOW+fstatregular-file and16 MiBsize checks; - Missing files still initialize cleanly, while any invalid UTF-8, corrupt JSON, or non-object schema now fails closed with
BrowserProfileError(leaving the original file untouched and emitting only line/column numbers without echoing secrets); - Explicit full resets (
clear_state(None)orreplace_all=True) remain available for deliberate recovery.
P1-4: Extension Session TTL Silently Expiring Only While Popup Remains Open
The Chrome extension offers 15m, 1h, and 4h auto-expire TTL presets. Because the MV3 extension deliberately runs with zero background scripts or service workers, closing the popup halted its setInterval timer:
native_host.rs’s"sync"handler completely ignored thettlSecsfield sent by the popup;- Playwright
storageStateorigins(localStorageJWTs) carry no nativeexpiresfield; popup.js’spruneExpiredDomains()checked exact equalityliveDomains.has(dom), skipping cleanup when only subdomain cookies were listed under a parent domain TTL.
If a user synced with a 15m TTL and closed the popup, localStorage tokens remained injectable from ~/.sessfork/state.json indefinitely.
The fix (coordinated across Chrome extension, Rust native_host.rs + storage.rs, and Python state.py):
native_host.rsnow validatesttlSecs(0..=604800), clamps synced cookieexpires, and atomically writes0600TTL sidecar files (ttl.jsonand.sessfork-ttl.json), pruning expired domains on"status"and"clear";- Both Rust
load_storage_state_fileand Pythonload_storage_stateenforce TTL sidecar filtering on every read, guaranteeing expiredlocalStorageJWTs are never re-hydrated even if the popup is never reopened; popup.jsnow uses subdomain-awarehostMatchesDomainchecks and syncs authoritativedomainTtlsfrom the native host.
P1-5: Unredacted Query Secrets & Token Prefixes in Extension IDOR Reports
In extension/idor_engine.js, candidate endpoint filtering stripped #fragment but preserved full ?search query strings. Meanwhile, scrubSensitiveText caught JWTs, sk_live, ghp, gho, creem, sbp_, AIza, AKIA, Bearer, and emails—but missed sensitive query parameters (?token=, ?access_token=, ?api_key=, ?code=, ?signature=, ?x-amz-security-token=), URL userinfo (https://user:pass@), and newer prefixes like github_pat_, ghu_/ghs_/ghr_, sk-proj-, sk-ant-, ntn_, glpat-, and xoxb-.
The fix: Expanded scrubSensitiveText with SENSITIVE_QUERY_PARAM_RE and modern token patterns, added redactUrlForDisplay, and applied redaction consistently across response snapshots (summarizeResponseForSnapshot), popup rendering (popup.js), and exported HTML reports—while keeping benign query params like ?org_id=42 intact for endpoint testing.
P1-6: Supply-Chain Asymmetry in install.ps1
While install.ps1 rigorously verified SHA256SUMS.txt hashes for sessfork-mcp-windows-x64.zip and sessfork-extension.zip, its Moli bootstrap block silently downloaded an unpinned, unhashed third-party script from releases/latest and ran it with -ExecutionPolicy ByPass:
Invoke-WebRequest -Uri "https://github.com/lexmount/moli/releases/latest/download/moli-installer.ps1" -OutFile $MoliInstaller -UseBasicParsing
& powershell -NoProfile -ExecutionPolicy ByPass -File $MoliInstaller
And at the top of the file, $Version defaulted to querying GitHub releases/latest rather than pinning a release tag.
The fix (install.ps1): Pinned $PinnedDefaultVersion = "v0.4.2" (matching install.sh, with latest strictly opt-in), stopped auto-downloading/executing third-party installers by default when moli.exe is missing, and required explicit SESSFORK_INSTALL_MOLI=1 + 64-hex SESSFORK_MOLI_INSTALLER_SHA256 verification + RemoteSigned when automated Moli installation is requested.
3. Five P2 Defense-in-Depth Hardening Improvements
Alongside splitting chrome.py’s SQL query into two static constants to eliminate the SAST alert, we closed five P2 hardening items:
- LevelDB parser memory bounds (
src/sessfork/localstorage.py): Cappedsnappy_decompressat16 MiB(MAX_SNAPPY_UNCOMPRESSED_BYTES) with incremental bounds checks on literals/copies, bounded WAL batch buffering at16 MiB, guardedshared > len(prev_key)in_iter_block_entries, and rejected@userinfo in_parse_localstorage_user_key. - Read-side
O_NOFOLLOW& key cache permission checks (src/sessfork/crypto.py,rust/sessfork-mcp/src/browser.rs):_load_key_cache_dictnow openskeys.jsonwithO_NOFOLLOWand enforcesfstatownership +0600mode (failing closed on0644caches);tool_file_uploadadds--profiles-dirandactive_default_storage_statetoforbidden_dirs/forbidden_files. - Eliminating post-reap
killpgPID-reuse windows (rust/sessfork-mcp/src/api_server.rs,handoff.rs): Added areaped: boolflag solibc::killpg(pid, SIGKILL)is never called afterchild.try_wait()has already reaped the process;validated_handoff_end_hostalso blocks public suffixes (github.io,co.uk) when collecting final handoff URLs. - Uniform
localhost/ IP literal matching (chrome.py,localstorage.py,state.py): Aligned Python matchers with Rust’shost_matches_domainsoevil.127.0.0.1andevil.localhostare never accepted as subdomains of127.0.0.1orlocalhost. - Subprocess pipe cleanup (
examples/genericagent-sop/sessfork_mcp_client.py): Explicitly closedstdin,stdout, andstderrin__exit__, eliminating testResourceWarnings.
4. Verification Results & Honest Boundaries (Not tested ≠ clean)
After all fixes and regression tests landed, we ran the full verification suite in isolated temporary sandboxes (zero access to real user browser profiles or ~/.sessfork/*):
- Python unit suite (
unittest discover -s tests -v):69 / 69passed (zeroResourceWarnings). - Rust unit tests & Clippy (
cargo test --locked --all-targets && cargo clippy --locked --all-targets -- -D warnings):78 / 78passed, 0 warnings. - Adversarial security harness (
scripts/security_verify.pyagainst the newly built releasesessfork-mcp+moli 1.1.29):29 / 29 PASS(failed=0). - Rust MCP live E2E (
test_rust_mcp_e2e.pyagainst the release binary):11 / 11passed.
In keeping with Not tested ≠ clean, here is what remains outside this run’s live execution envelope:
- Everything ran on macOS
arm64; Windows live execution ofinstall.ps1/ Win32 Job Objects and Linuxsecret-tool/ OpenSSL behavior were not exercised on live Windows/Linux hosts in this round. - Extension UI controls were verified via Node VM harnesses and unit checks rather than interactive clicking inside a live Chrome window.
- Lower-priority P2 items (such as
ui_server.pyprinting?token=to stdout and expanding multi-label cloud PSL entries) remain queued for a follow-up cleanup.
5. Five Audit Habits Worth Keeping for Any Credential-Handling Agent Tool
- Treat every “inspect-then-act” CDP step as a TOCTOU candidate: Whenever a
frameIdcan navigate betweenPage.getFrameTreeand execution, enforcelocation.origininside the evaluated world itself. - Never fail open to
{}on corrupt state files: Silent fallbacks turn a single disk glitch into total credential loss on the next incremental write. - Never rely on an ephemeral UI popup to enforce credential TTLs: If the extension has no background worker, the host and consumer loaders must enforce expiration on disk and on read.
- Check installer symmetry: Hashing your own binary means very little if the next block pipes an unpinned upstream
latestscript straight intoByPass. - Patch first, publish second: Keep every draft and write-up offline until the fixed release is shipped.
More Articles (22)
- EN Zero-Dependency Multi-Profile AI Browser Isolation in 1.18 MiB of Rust: Per-Context Proxy Guards, 42 MiB Moli Pools, and 2-Phase Human Handoff
- 中文 零依赖构建多身份 AI 浏览器隔离池:Per-Context 代理防漏、42 MiB 进程编排与两阶段无头/有头接管实测
- 中文 从一条 SAST 假阳性 SQL 告警出发:我们如何对 sessfork 做了全链路白盒安全审计并修掉 6 个真实 P1 缺陷
- 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 空闲回收
- EN Why Giving an AI Browser MCP Unrestricted File Upload Leaks Your Cookies — And How We Built Fail-Closed Native Uploads in Rust
- 中文 为什么别给 AI 浏览器 MCP 开全盘文件上传:原生 CDP 零拷贝与 4 道 Fail-Closed 防线
- 中文 拆完 14.5K★ GenericAgent 源码后,我把它的 3 个浏览器实战绝招安全搬进了 913 KB 纯 Rust MCP(17/17 对抗测试全绿)
- 中文 零依赖工程实践:如何在 56ms 冷启动与 0 第三方库约束下,给 claimcite 加上 LaTeX、Git 增量门禁与防注入安全围栏
- EN Zero-Dependency Engineering: Adding BibTeX/LaTeX, Git-Diff Gating, SARIF, and Security Confinement to claimcite Without Losing a Millisecond
- EN Catching Silent AI Citation Hallucinations With Zero-Dependency Deterministic Verification
- 中文 零依赖、可复现地抓出 AI 引文幻觉:从 4 类隐蔽学术造假到本地 xerj:// 字节跨度核验
- 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%