Skip to content

feat(browser-engine): add isolated oc-preview scheme handler with open-handle confinement - #281

Merged
Hona merged 8 commits into
devfrom
previews/pr1-engine-scheme
Nov 20, 2026
Merged

Hona merged 8 commits into
devfrom
previews/pr1-engine-scheme

Conversation

@Hona

@Hona Hona commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Lands PREVIEWS PR 1 (apps/browser-engine + crates/browser-policy + crates/browser-pane protocol): the isolated oc-preview:// custom scheme handler, per-preview ephemeral CefRequestContext via WS-1's shared #288 ContextPool, parent-handle-relative pre-open walk + open-handle kernel path confinement (including Windows Cloud Filter / OneDrive placeholder support), bounded per-grant off-IO-thread local file streaming, strict CSP / Connection-Allowlist / verified deferred lockdown prefs, and credential-free async proxy protocol for remote workspace files and artifacts (anomalyco/opencode#63002).

Round-2 notes/review-rd281.md Blockers Closed (Delta over ed23e2ca)

  1. Pre-init window closed fail-closed (apps/browser-engine/src/{context,engine,handlers,prompts,preview/{context,handler,mod}}.rs):
    • Added fail-closed ContextPool::is_tab_ready(&self, tab_id: u64) -> bool (tracks default_tabs; returns false for any unknown, closed, uninitialized, or failed-pref tab; true for live Default tabs or initialized + pref-verified + on_initialized-completed isolated tabs) and clear_pending_load(tab_id) (coordinated in ORCHESTRATOR-inbox.md with WS-1 for #292).
    • Added monotonic generation token on ResolvedContext / ManagedTab / DeferredOutcome::{Load,Refuse} and pruned ready_loads in release_tab.
    • Deferred ALL uninitialized isolated contexts (!is_init) onto about:blank; gated HostMsg::{CdpCall,Navigate,Back,Forward,Reload,ContextMenuAction,ClearSite,ClearSiteCache,SiteCookies,SetInspect,HighlightNode,Emulate} and pending_clears on self.contexts.is_tab_ready(tab_id).
    • Added PreInitBlockResourceHandler in IsolatedContextHandler::resource_request_handler plus context_ready: Arc<AtomicBool> checks in TabRequestHandler::{on_before_browse,on_open_urlfrom_tab}, TabResourceRequestHandler::{on_before_resource_load,on_resource_redirect}, TabLifeSpanHandler::on_before_popup, and PreviewResourceFilter::on_before_resource_load — cancelling EVERY non-about:blank navigation, subresource, worker, beacon, redirect, or popup before on_request_context_initialized finishes verifying prefs.
    • Moved PreviewSchemeHandlerFactory registration into ContextHooks::on_initialized so the scheme handler factory is registered (and PreviewGrant::mark_ready() set) only after apply_context_prefs has verified all three CEF 156 lockdown prefs (webrtc.ip_handling_policy, net.network_prediction_options, net.quic_allowed).
  2. Windows Cloud Filter (OneDrive / iCloud / Dropbox / Google Drive) + parent-handle-relative NtCreateFile walk (apps/browser-engine/src/preview/handle_path.rs):
    • Replaced full-path child re-opens with parent-handle-relative NtCreateFile (OBJECT_ATTRIBUTES.RootDirectory) starting from the verified pinned workspace root handle, eliminating the Windows intermediate-walk check-then-use SMB/NTLMv2 race.
    • Replaced blanket FILE_ATTRIBUTE_REPARSE_POINT rejection with GetFileInformationByHandleEx(FileAttributeTagInfo) allow-listing only non-redirecting Windows Cloud Filter placeholder tags (IO_REPARSE_TAG_CLOUD*: (tag & !0x0000_F000) == 0x9000_001A and legacy IO_REPARSE_TAG_ONEDRIVE: 0x8000_0021), strictly refusing bit-29 name surrogates (symlinks, junctions, mount points, WSL symlinks), APPEXECLINK, and every unknown tag.
    • For verified Cloud Filter placeholder directories/files only, re-opens relative to the same verified parent handle without FILE_OPEN_REPARSE_POINT so cldflt.sys hydrates/traverses the placeholder, then re-verifies FILE_TYPE_DISK, directory/non-directory attribute, FileAttributeTagInfo tag, GetFinalPathNameByHandleW local \\?\<drive>:\ containment, preview_allowed, and post-open root pin. (Known residual: for a Cloud Filter placeholder leaf only, a local attacker with write permission inside the workspace could attempt to swap the leaf between the initial tag check and the hydrating re-open; post-open final-path and reparse-tag verification still strictly confines any served bytes.)
  3. Bounded per-grant PreviewIoPool quota + panic unwind isolation (apps/browser-engine/src/preview/{io_pool,mod,handler}.rs):
    • Added per-grant RAII IoPermit enforcing MAX_GRANT_IO_JOBS = 32 inside the 256-slot global queue so one abusive preview tab cannot starve other preview tabs.
    • Wrapped every worker job in std::panic::catch_unwind with an on_panic callback that marks handler state canceled (recovering cleanly from poisoned mutexes via unwrap_or_else(|e| e.into_inner())), cancels the CEF open/skip/read callback, and releases the IoPermit without terminating worker threads.
  4. Remote root lexical hardening (crates/browser-policy/src/lib.rs):
    • Hardened normalize_root_lex to reject \\.\... (device namespace), \??\... (NT object namespace), extended \\?\... unless strictly \\?\<drive>:\... (rejecting \\?\UNC\..., \\?\Volume{...}, \\?\GlobalRoot\...), leading ///..., internal // (C://Windows, /etc//ssh), drive-relative paths (C:Windows), and non-absolute roots.

Round-1 notes/review-rd281.md Blockers Already Confirmed Closed at ed23e2ca


Empirical CEF 156.0.26 & Windows cldflt.sys Findings (proof/previews/pr1-engine-proof.json: ALL_PASS)

  1. Pre-init window race (live): Pipelining CdpCall("Runtime.evaluate") + Navigate + ClearSiteCache + Page.navigate in the exact same write burst as OpenTab(local preview) returned ok: false, message: "browser.context.initializing" for both CdpCall and ClearSiteCache, emitted 0 leaked HTTP hits, and loaded LocalPreviewA cleanly once on_request_context_initialized verified prefs and registered PreviewSchemeHandlerFactory.
  2. blob: iframe inheriting Connection-Allowlist: (response-origin);webrtc=block (live A/B on CEF 156.0.26):
    • Plain web control (Default context, no header, blob: iframe running TURN-TCP + STUN UDP): tcpHits: 1, udpHits: 3 (both connect).
    • Cross-origin fetch("http://localhost:.../blob-iframe-cross") from a blob: iframe: executed cleanly (loaded: true) and was blocked on BOTH AllowlistOnly (Default context, ONLY Connection-Allowlist header, zero prefs) and LocalPreviewA (crossOk: false, blobIframeCrossFetchLeakedHits: 0).
    • TURN-TCP + STUN UDP RTCPeerConnection from a blob: iframe on BOTH AllowlistOnly (Default context, header-only, zero prefs) and LocalPreviewA (isolated preview tab): tcpTurnHits: 0, udpHits: 0 — Chromium 156 actively inherits webrtc=block into blob: sub-frames at the browser-process Mojo binder layer (No binder found for interface network.mojom.MdnsResponder for the frame/document scope) and immediately terminates the hostile renderer (RESULT_CODE_KILLED_BAD_MESSAGE, reason 123) before emitting a single packet.
  3. Windows Cloud Filter (cldapi.dll + cldflt.sys) hydrated & dehydrated placeholder proof (live, scratch sync root, zero OneDrive touched):
    • Registered synthetic pure-Win32 sync root OpenCodePreviewCloudProof (8b3f52d1-90a4-4e55-b0c1-2d3e4f5a6b7c, zero Explorer nav-pane entry) in scratch C:\tmp\opencode\previews\pr1-proof\cloud_ws:
      • Placeholder dir docs: attrs=0x00000410, tag=0x9000601A (IO_REPARSE_TAG_CLOUD_6) -> ALLOWED.
      • Hydrated placeholder docs/index.html: attrs=0x00000420, tag=0x9000601A (IO_REPARSE_TAG_CLOUD_6) -> loaded cleanly ("CloudHydratedOK").
      • Dehydrated placeholder docs/dehydrated.txt: attrs=0x00401620, tag=0x9000401A (IO_REPARSE_TAG_CLOUD_4, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS) -> re-opened without FILE_OPEN_REPARSE_POINT, hydrated via cldflt.sys CF_CALLBACK_TYPE_FETCH_DATA (hydrations: 1), returned 200 "CLOUD_HYDRATED_OK!".
      • Hostile NTFS junction docs/junc_out inside the same Cloud Filter directory: attrs=0x00000410, tag=0xA0000003 (IO_REPARSE_TAG_MOUNT_POINT) -> juncBlocked: true.
    • Unregistered & verified clean in finally (CLEANUP unreg=0x80070002 cfCheck=0x80070002 exists=False syncRootManagerKey=False explorerNavPane=False clsid=False).
  4. Per-grant PreviewIoPool quota (live): Simultaneous 48-read burst on Tab 1 (tab1BurstOk: 35, excess above 32-job cap cancelled cleanly off IO thread) + 8 reads on Tab 20 -> tab20ConcurrentOk: 8/8 (zero cross-tab starvation).
  5. Previously settled CEF 156.0.26 live findings (all still ALL_PASS):
    • DownloadImage vs ResourceRequestHandler: web control 2 hits vs local & artifact preview 0 hits.
    • Verified CEF 156 profile prefs (webrtc.ip_handling_policy, net.network_prediction_options, net.quic_allowed all read back Set) + Connection-Allowlist A/B (tcpTurnHits: 0, udpHits: 0, crossOk: false; preview cands: 0, tcpTurnHits: 0, udpHits: 0).
    • Remote 206 (bytes=10-13/16 -> "ABCD"), extension-only MIME override (text/plain; charset=utf-8), per-segment encoding (site/a%3Fb%23c.txt), invalid Range normalized away, artifact 206 rejected, 15/15 broad local/remote roots refused (incl. C://Windows, C:Windows, \\?\UNC\..., ///etc/ssh/dir, \\.\C:\Windows, \??\C:\Windows), 34/34 hostile local probes + 8/8 Web Worker escapes blocked, context menu sanitized + SaveImage 0 downloads, file_chooser_blocked: true.
  6. macOS (fcntl(F_GETPATH)) & Linux (/proc/self/fd + openat) open-handle paths:
    • Linux: Audited statically by reading (openat(O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) intermediate walk + O_NONBLOCK | O_NOFOLLOW leaf + S_IFREG + /proc/self/fd + (dev, ino) pin without mutable st_ctime); not executed live on Linux in this run.
    • macOS: Same openat walk + fcntl(F_GETPATH) + immutable st_birthtime/nsec pin; compiled by CI build-macos and queued with PROOF-FARM for headless execution on air via proof/previews/mac-handle-path-proof.ts (not yet executed live at push time).

Build & Guardrail Verification

  • pwsh scripts/guardrails.ps1: 5/5 passed
  • apps/browser-engine --bins: compiled, 0 warnings
  • cargo check --workspace: passed, 0 warnings
  • cargo check -p browser-pane --no-default-features: passed, 0 warnings
  • pwsh scripts/web.ps1 -Check (wasm32): passed, 0 warnings
  • proof/previews/engine-security-proof.ts -> proof/previews/pr1-engine-proof.json: ALL_PASS

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

PR test build retired — merged into dev. Install or auto-update OpenCode (Rune) from https://anoma.ly/release/opencode/desktop-rune/dev/macos-arm64-dmg.

…heme

# Conflicts:
#	crates/browser-pane/src/client.rs
#	crates/browser-policy/src/lib.rs
Hona added a commit that referenced this pull request Nov 20, 2026
…osed, and drop on last tab close (#288)

Hardens `apps/browser-engine/src/context.rs` as the single shared `CefRequestContext`
creator across WS-1, WS-9 (`#274`), PREVIEWS (`#281`), and BROWSER-TOOLS (resolving
`notes/review-rd274.md` Finding 5):

- **Partitioned scopes & canonical keys (`ContextKind` / `ContextKey`):**
  - `Default` -> global persistent profile (`OPENCODE_BROWSER_PROFILE/Default`).
  - `Preview { workspace, grant }` -> `ContextKey::Preview { workspace, grant }` (distinct per
    workspace and grant; never shares across workspaces or with artifacts).
  - `Artifact { artifact_id }` -> `ContextKey::Artifact(artifact_id)` (separate namespace from
    workspace previews).
  - `Private` -> `ContextKey::Private(tab_id)` (unique per private tab; never shared).
  - `RemoteServer { server_id, proxy }` -> `ContextKey::RemoteServer(server_id)` keyed by
    canonical `ServerKey::as_str()` identity (never display name; keeps `#[serde(alias =
    "partition")]` for wire compatibility).
- **Fail closed on every path:** Empty keys return `browser.context.invalid`; non-loopback
  proxies return `browser.proxy.invalid`; `cef::request_context_create_context` or
  `browser_host_create_browser_sync` failure returns `browser.context.unavailable` with an
  explicit pre-create guard forbidding `!context.is_default() && req_ctx.is_none()`. On
  desktop, `App::default_browser_context()` always returns `RemoteServer` on non-sidecar
  servers (never silently falling back to `Default` when an older engine lacks
  `Ready.partitions`), and pop-ups from isolated contexts never inherit into `Default`.
- **Ref-counted teardown & zero disk writes:** Every non-`Default` context runs strictly
  in memory (`cache_path: ""`, `persist_session_cookies: 0`), disables WebRTC non-proxied
  UDP/multiple routes, DoH, QUIC, and DNS prefetching, strips `file_roots`, and drops
  immediately when its last tab closes (`ContextPool::release_tab`, closing connections and
  wiping cookies/storage/caches/service workers; `RemoteServer` proxy configs remain in
  `remote_proxies` until `DropContext`).
- **Shared hooks for PREVIEWS (`#281`) & WS-9 (`#274`):** Adds `ContextHooks`
  (`resource_filter`, `exclude_default_cookie_schemes`, `on_created`) on
  `ContextPool::resolve_with_hooks` and `ContextKind::is_isolated()`, plus preserves
  `agent_driven` across Linux dmabuf `ReopenTabs`.
Hona added a commit that referenced this pull request Nov 20, 2026
…18..UP-122 (#295)

- Fold verified fleet PRs #278, #285, #287, #288, #289, #290, #291, and
  #293 (Rune dc8f7f72: #1301, #1302 focus rescue verified Send+Enter -> effort)
  into docs/upstream-sync/ledger.{json,md}
- Close UP-062 packaged-default regression (#278), UP-095-UI / UP-100 /
  UP-106 / UP-109 / UP-117 (#285, #289), and PRE-08 (#287); reassign
  UP-115, UP-116, UP-075 to BROWSER-UI
- Add separate Reviewed column for browser rows tracking retrospective
  security reviews on merged PRs (#245, #268, #272, #277, #288, #275, #287,
  #285, #289) and pre-merge holds (#274, #280, #281, #283, #286, #292, #294,
  and BROWSER-TOOLS PR 3+)
- Audit upstream anomalyco/opencode bfee96a859..2002222d13 (+6 commits:
  1 skipped, 5 added: UP-118..UP-122) and refine radar routing
Hona added 3 commits November 21, 2026 00:45
…loud Filter placeholders via NtCreateFile walk, cap per-grant I/O with unwind guard, and harden remote roots
@Hona
Hona merged commit 5d50c6f into dev Nov 20, 2026
7 checks passed
@Hona
Hona deleted the previews/pr1-engine-scheme branch November 20, 2026 16:36
Hona added a commit that referenced this pull request Nov 20, 2026
Hona added a commit that referenced this pull request Nov 20, 2026
…304)

- Fold verified merged PRs #280 (WS-9 crates/browser-extensions, confirmed),
  #281 (PREVIEWS oc-preview:// + ContextPool::is_tab_ready, confirmed third
  read + merge check), #297 (inline chat video + reply link menu, not
  reviewed before merge), #299 (WS-1 close_all_connections crash fix), and
  #300 (Rune eff95e80: #1304 roving-group rescue + #1291 monochrome SMIL
  animated icons completing UP-069 / WS-6)
- Update browser Reviewed column and note #287 eager-attach time_updated
  regression on UP-095-TOOLS
- Audit upstream anomalyco/opencode 2002222d13..fe8def6854 (+19 commits:
  7 skipped, 12 added: UP-123..UP-134)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant