Skip to content

[Windows] Fix WebView appdir local-host detection and align its resource-access mode - #36603

Merged
kubaflo merged 7 commits into
inflight/currentfrom
mattleibow-fix-windows-webview-appdir-detection
Jul 27, 2026
Merged

kubaflo merged 7 commits into
inflight/currentfrom
mattleibow-fix-windows-webview-appdir-detection

Conversation

@mattleibow

@mattleibow mattleibow commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description

On Windows the standard MAUI WebView is backed by MauiWebView, which maps the app's base/installed directory to the fixed local virtual host https://appdir/ via CoreWebView2.SetVirtualHostNameToFolderMapping(...). This PR fixes two issues in src/Core/src/Platform/Windows/MauiWebView.cs.

Issue 1 — local-host detection compared the raw string instead of the parsed host

IsUriWithLocalScheme decided whether a URL pointed at local appdir content with a raw prefix comparison:

uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)

Because this compares the raw string rather than the parsed URL, it also matched URLs whose real host merely starts with those characters:

  • https://appdir.example.com/page.html → parsed host is appdir.example.com, not appdir
  • https://appdir@host.example.com/page.html → parsed host is host.example.com (appdir is the userinfo)

Both were incorrectly treated as local appdir content, so the folder mapping was applied/kept for a host that isn't appdir. The same predicate is reused by the NavigationStarting handler, so both initial-load and navigation-time decisions were affected.

Fix: IsUriWithLocalScheme now parses the string with Uri.TryCreate(..., UriKind.Absolute, out var parsed) and returns true only when parsed.Scheme == Uri.UriSchemeHttps, the URL carries no userinfo, and parsed.Host is exactly appdir (ordinal, case-insensitive). It returns false when the string can't be parsed as an absolute URI. appdir is an arbitrary placeholder host, so matching it exactly is the correct behavior.

Issue 2 — the mapping used a broader resource-access mode than this host needs

All three mapping call sites passed CoreWebView2HostResourceAccessKind.Allow. For a host that just serves local app files this is broader than needed. DenyCors is the more appropriate mode for a local file-serving host, and it changes behavior only in one specific way (details below).

Fix: all three SetVirtualHostNameToFolderMapping call sites (LoadHtml, LoadUrl, NavigationStarting) now use DenyCors.

What DenyCors changes (and what it doesn't)

Straight from the CoreWebView2HostResourceAccessKind matrix:

Access from an appdir document Allow (before) DenyCors (now)
DOM sub-resources (<img>, <script src>, <link>, <iframe src>) ✅ ✅ unchanged
Same-origin fetch/XHR from a real https://appdir/ page (LoadUrl) ✅ ✅ unchanged
Cross-origin fetch/XHR to appdir (from a null-origin NavigateToString/LoadHtml document, or a cross-origin iframe) ✅ ⛔ no longer answered

So normal local content — images, CSS, scripts, fonts, iframes, and same-origin fetch on a real appdir page — keeps working. The only behavior change is the last row.

Intentional behavior change for one LoadHtml edge case

LoadHtml() uses NavigateToString, so that document has a null origin rather than the https://appdir origin. A script fetch/XHR to https://appdir/… from such a document is cross-origin and is no longer answered under DenyCors. This is intentional. If LoadHtml content specifically needs script-readable local data, the options are to load a real https://appdir/ page via LoadUrl (same-origin fetch works) or to use HybridWebView, which serves app content through WebResourceRequested.

NavigationStarting also now correctly calls ClearVirtualHostNameToFolderMapping when navigating to a URL whose parsed host is not appdir.

API changes

No public API additions — PublicAPI.Unshipped.txt is unchanged. The only new/changed members are two internal helpers on the (public) MauiWebView, exposed to the device-tests assembly via InternalsVisibleTo so the host-detection logic can be tested without a live WebView2:

namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}

Tests

Added coverage in src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs (Windows-only, since MauiWebView is Windows-only). There was previously no coverage for the host detection or the mapping mode.

Host-detection (lightweight, pure static calls via the internal helpers):

  • IsUriWithLocalScheme: https://appdir/… and https://APPDIR/… → true; http://appdir/… → false; https://appdir.example.com/… → false; https://appdir@host.example.com/… → false; https://user:pass@appdir/… → false; unrelated host → false; relative → false.
  • IsLocalAppDirUrl: relative URLs → local; https://appdir/… → local; subdomain / userinfo / external host → not local.

Device tests (real WebView2):

  • Local sub-resource (<script src>) referenced from https://appdir/ still loads.
  • Same-origin fetch from a real https://appdir/ page still completes (appdir-fetch-test.html).
  • A cross-origin iframe (opaque-origin data: URL) cannot read an appdir file via fetch (appdir-iframe-parent.html), reported back via postMessage.
  • LoadHtml content (null-origin document) doing a cross-origin fetch of an appdir file does not complete.
  • A script fetch does not raise NavigationStarting (confirming fetch/XHR are sub-resource requests, so the mapping mode governs them).
  • Navigating to a non-appdir host clears the mapping.

New Resources/Raw/appdir-*.{html,js} assets back the device tests.

The Windows WebView (MauiWebView) mapped the app directory to the
https://appdir/ virtual host and decided whether a URL pointed at that
local content with a raw string prefix comparison:

    uri.StartsWith("https://appdir", ...)

Because this compared the raw string rather than the parsed URL, hosts
that merely began with the same characters were wrongly treated as
local content, e.g. https://appdir.example.com/ (host is
appdir.example.com) and https://appdir@host.example.com/ (host is
host.example.com, appdir is the userinfo). In both cases the local
folder mapping was applied/kept for a host that was not appdir.

Changes (all in MauiWebView.cs):
- Rewrite IsUriWithLocalScheme to parse the string with Uri.TryCreate
  and return true only when the parsed scheme is https AND the parsed
  host is exactly "appdir" (ordinal, case-insensitive).
- Add internal IsLocalAppDirUrl which keeps the existing behaviour that
  relative URLs stay local, routing LoadUrl's local detection through a
  single, unit-testable helper.
- Use CoreWebView2HostResourceAccessKind.DenyCors instead of Allow at
  all three SetVirtualHostNameToFolderMapping call sites (LoadHtml,
  LoadUrl, NavigationStarting). DenyCors still serves normal local
  sub-resources (images, scripts, css, fonts, iframes) and is the
  recommended mode for a local file-serving host.

Tests (Core.DeviceTests, Windows):
- Lightweight host-detection theories exercising IsUriWithLocalScheme
  and IsLocalAppDirUrl directly (appdir, APPDIR, relative,
  appdir.example.com, appdir@host.example.com, wrong scheme, ...).
- Device test confirming a local sub-resource referenced from
  https://appdir/ still loads after switching to DenyCors.
- Device test confirming that navigating to a non-appdir host clears
  the mapping so appdir sub-resources are no longer served.
- New Resources/Raw assets (appdir-subresource-test.html/.js) used by
  the device tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
Copilot AI review requested due to automatic review settings July 15, 2026 22:13
@mattleibow
mattleibow temporarily deployed to copilot-pat-pool July 15, 2026 22:13 — with GitHub Actions Inactive
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36603

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36603"

@mattleibow
mattleibow temporarily deployed to copilot-pat-pool July 15, 2026 22:13 — with GitHub Actions Inactive
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@mattleibow

Copy link
Copy Markdown
Member Author

/azp run maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes Windows MauiWebView local appdir URL classification to use parsed URI host matching (preventing false positives like appdir.example.com / userinfo tricks) and tightens the WebView2 virtual host folder mapping access mode to DenyCors. Adds Windows device tests and raw assets to cover both the host-detection logic and sub-resource loading behavior under the new mapping mode.

Changes:

  • Reworked appdir detection to require https + exact parsed host match (and added an internal helper to keep relative URLs local).
  • Switched WebView2 folder mapping access kind from Allow to DenyCors across all mapping call sites.
  • Added Windows device tests + raw HTML/JS assets to validate sub-resource loading and ensure non-appdir navigations don’t retain the mapping.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/Core/src/Platform/Windows/MauiWebView.cs Fixes appdir detection by parsing URIs and tightens WebView2 folder mapping access kind (DenyCors).
src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs Adds unit-like classification tests + Windows device tests validating sub-resource behavior and mapping clearing.
src/Core/tests/DeviceTests/Resources/Raw/appdir-subresource-test.html Test HTML page served from https://appdir/ that references a relative script.
src/Core/tests/DeviceTests/Resources/Raw/appdir-subresource-test.js Test script that mutates document.title to prove it was served/loaded.

Copilot AI review requested due to automatic review settings July 17, 2026 19:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

mattleibow and others added 2 commits July 18, 2026 16:23
IsLocalAppDirUrl already parsed the input into a Uri, then called
IsUriWithLocalScheme(uri.AbsoluteUri), which re-parsed the same URL from
a string. Factor the scheme/host check into a private Uri-based overload
and reuse it from both paths:

- IsUriWithLocalScheme(Uri): the actual absolute + https + host=="appdir"
  check on an already-parsed Uri (no re-parsing).
- IsUriWithLocalScheme(string?): parses once, delegates to the Uri overload
  (kept internal; used by the NavigationStarting handler and tests).
- IsLocalAppDirUrl: passes its already-parsed Uri straight to the Uri
  overload instead of round-tripping through AbsoluteUri.

Behavior is unchanged - verified identical results across all detection
cases (including the appdir.example.com subdomain and appdir@host userinfo
cases). No public API change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
…lization)

"appdir" is an arbitrary placeholder virtual host mapped to the app
directory via SetVirtualHostNameToFolderMapping, so only the exact host
"appdir" serves local content. Expand the comment on IsUriWithLocalScheme
to record the WebView2 host-canonicalization rules this matches:

- Case-insensitive: WebView2 canonicalizes host names case-insensitively
  ("APPDIR" == "appdir"); System.Uri already lower-cases Host, so the
  OrdinalIgnoreCase compare is belt-and-suspenders.
- Trailing dot ("appdir.") is intentionally a different host and is not
  treated as local, matching WebView2 (which does not normalize it).

Comment-only; no behavior change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Jul 19, 2026
@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates labels Jul 19, 2026
@PureWeen PureWeen added the p/0 Current heighest priority issues that we are targeting for a release. label Jul 24, 2026
@MauiBot

MauiBot commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

AI Review Summary

@mattleibow — new AI review results are available based on this last commit: f796f68.

Gate Inconclusive Confidence Low Platform Windows


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ⚠️ INCONCLUSIVE

Platform: WINDOWS · Base: main · Merge base: 997d875b

🩺 Base branch does not compile — the without-fix build failed. The gate's "does the test fail without the fix" check is unreliable here; this usually means main is broken or a merge-base file went missing. Investigate before trusting this gate.

D:\a\1\s\src\Core\tests\DeviceTests\Handlers\WebView\WebViewHandlerTests.Windows.cs(28,39): error CS0117: 'MauiWebView' does not contain a definition for 'IsUriWithLocalScheme' [D:\a\1\s\src\Core\test...

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 WebViewHandlerTests (IsUriWithLocalSchemeClassifiesByParsedHost, IsLocalAppDirUrlClassifiesCorrectly, LocalSubResourceFromAppDirLoads, NonAppDirNavigationDoesNotReceiveLocalMapping, LoadHtmlScriptFetchOfAppDirResourceDoesNotSucceed, ScriptFetchDoesNotRaiseNavigationStarting, SameOriginFetchFromAppDirPageSucceeds, CrossOriginIframeFetchOfAppDirResourceIsDenied) Category=WebView 🛠️ BUILD ERROR ✅ PASS — 254s
🔴 Without fix — 📱 WebViewHandlerTests (IsUriWithLocalSchemeClassifiesByParsedHost, IsLocalAppDirUrlClassifiesCorrectly, LocalSubResourceFromAppDirLoads, NonAppDirNavigationDoesNotReceiveLocalMapping, LoadHtmlScriptFetchOfAppDirResourceDoesNotSucceed, ScriptFetchDoesNotRaiseNavigationStarting, SameOriginFetchFromAppDirPageSucceeds, CrossOriginIframeFetchOfAppDirResourceIsDenied): 🛠️ BUILD ERROR · 292s

Error-relevant lines (filtered from the build log):

D:\a\1\s\src\Core\tests\DeviceTests\Handlers\WebView\WebViewHandlerTests.Windows.cs(28,39): error CS0117: 'MauiWebView' does not contain a definition for 'IsUriWithLocalScheme' [D:\a\1\s\src\Core\tests\DeviceTests\Core.DeviceTests.csproj::TargetFramework=net10.0-windows10.0.19041.0]
D:\a\1\s\src\Core\tests\DeviceTests\Handlers\WebView\WebViewHandlerTests.Windows.cs(39,39): error CS0117: 'MauiWebView' does not contain a definition for 'IsLocalAppDirUrl' [D:\a\1\s\src\Core\tests\DeviceTests\Core.DeviceTests.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Build FAILED.
🟢 With fix — 📱 WebViewHandlerTests (IsUriWithLocalSchemeClassifiesByParsedHost, IsLocalAppDirUrlClassifiesCorrectly, LocalSubResourceFromAppDirLoads, NonAppDirNavigationDoesNotReceiveLocalMapping, LoadHtmlScriptFetchOfAppDirResourceDoesNotSucceed, ScriptFetchDoesNotRaiseNavigationStarting, SameOriginFetchFromAppDirPageSucceeds, CrossOriginIframeFetchOfAppDirResourceIsDenied): PASS ✅ · 254s

(no coded error found; showing last 1200 chars)

 can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Core\src\Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Platform\Windows\Styles\WindowRootViewStyle.xaml(31,17): XamlCompiler warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive with the respective binding data context and marking the type declaration with the 'WinRT.GeneratedBindableCustomProperty' attribute or the 'Microsoft.UI.Xaml.Data.Bindable' attribute. If you are unable to do either but can ensure the data type is attributed correctly, then you can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Core\src\Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
    11 Warning(s)
    0 Error(s)

Time Elapsed 00:02:57.62
  Passed: 22
  Failed: 0
  Skipped: 0
  Total: 22
  Tests completed successfully

⚠️ Failure Details

  • 🛠️ WebViewHandlerTests (IsUriWithLocalSchemeClassifiesByParsedHost, IsLocalAppDirUrlClassifiesCorrectly, LocalSubResourceFromAppDirLoads, NonAppDirNavigationDoesNotReceiveLocalMapping, LoadHtmlScriptFetchOfAppDirResourceDoesNotSucceed, ScriptFetchDoesNotRaiseNavigationStarting, SameOriginFetchFromAppDirPageSucceeds, CrossOriginIframeFetchOfAppDirResourceIsDenied) without fix: build failed before tests could run
    • D:\a\1\s\src\Core\tests\DeviceTests\Handlers\WebView\WebViewHandlerTests.Windows.cs(28,39): error CS0117: 'MauiWebView' does not contain a definition for 'IsUriWithLocalScheme' [D:\a\1\s\src\Core\test...
📁 Fix files reverted (1 files)
  • src/Core/src/Platform/Windows/MauiWebView.cs

📱 UI Tests — ViewBaseTests

Detected UI test categories: ViewBaseTests

✅ Deep UI tests — 115 passed, 0 failed across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
ViewBaseTests 115/115 ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

📋 Pre-Flight — Context & Validation

Issue: #36603 - PR discussion only (no separate linked issue found)
PR: #36603 - [Windows] Fix WebView appdir local-host detection and align its resource-access mode
Platforms Affected: Windows
Files Changed: 1 implementation, 5 test/resource

Key Findings

  • The PR fixes an unsafe raw-prefix check for the Windows WebView2 virtual host https://appdir/ by parsing the URI and requiring exact host appdir, HTTPS, and no userinfo.
  • The PR also changes all appdir folder mappings from Allow to DenyCors, including LoadHtml(html, null), which changes script-readable packaged resource behavior for HtmlWebViewSource/NavigateToString.
  • The branch contains unrelated dirty worktree changes outside the PR commit; try-fix candidates are therefore isolated to the WebView files and broad restore commands are avoided to preserve pre-existing changes.

Code Review Summary

Verdict: NEEDS_CHANGES
Confidence: low
Errors: 1 | Warnings: 0 | Suggestions: 0

Key code review findings:

  • ✗ src/Core/src/Platform/Windows/MauiWebView.cs:63 changes the LoadHtml(html, null) appdir mapping to DenyCors, which blocks script fetch/XHR from the null-origin NavigateToString document to packaged app resources that previously worked.

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #36603 Exact parsed appdir host detection plus uniform DenyCors mapping at LoadHtml, LoadUrl, and NavigationStarting ⚠️ INCONCLUSIVE (Gate) MauiWebView.cs, Windows WebView device tests/resources Original PR; gate could not build/run in prior step

🔬 Code Review — Deep Analysis

Code Review — PR #36603

Independent Assessment

What this changes: Windows MauiWebView now parses appdir URLs by exact URI host/scheme instead of raw prefix matching, and changes all SetVirtualHostNameToFolderMapping calls from Allow to DenyCors. It adds Windows WebView2 device tests and raw assets for host classification and appdir resource access.

Inferred motivation: Fix unsafe false-positive local-host detection (appdir.example.com, userinfo tricks) and tighten WebView2 local-resource exposure.

Reconciliation with PR Narrative

Author claims: The parsed-host fix prevents incorrect local mapping, and DenyCors intentionally blocks only cross-origin fetch/XHR to appdir while preserving DOM subresources and same-origin appdir fetches.

Agreement/disagreement: The host-parsing fix is sound. I disagree that the LoadHtml behavior change is safe as-is: default HtmlWebViewSource/LoadHtml content using script fetch('relative-file') loses access to packaged app resources.

Prior Review Reconciliation

Prior ❌ Error Finding Source Status Evidence
[major] Changing LoadHtml mapping to DenyCors breaks HtmlWebViewSource script fetch/XHR of relative app resources. MauiBot inline/top-level reviews ❌ Unresolved src/Core/src/Platform/Windows/MauiWebView.cs:63 still uses DenyCors; LoadHtmlScriptFetchOfAppDirResourceDoesNotSucceed now asserts the formerly-allowed fetch fails.

Blast Radius Assessment

  • Runs for all instances: Partially — all Windows MauiWebView appdir mappings use the new access mode.
  • Startup impact: No.
  • Static/shared state: No.
  • Platform scope: Windows WebView2 local-content behavior.

CI Status

  • Required-check result: undetermined/tool-unavailable — gh pr checks --required failed because gh is unauthenticated.
  • Classification: undetermined. Public REST check-runs for head f796f682... show maui-pr and maui-pr-devicetests success, but required-check status could not be verified.
  • Action taken: confidence capped low.

Findings

❌ Error — LoadHtml local-resource script fetch is a compatibility regression

src/Core/src/Platform/Windows/MauiWebView.cs:63 changes the LoadHtml(html, null) appdir mapping to DenyCors. Because LoadHtml uses NavigateToString, that document has an opaque/null origin; relative script fetches resolve through the injected https://appdir/ base URL and are now denied. The new test at WebViewHandlerTests.Windows.cs:154-166 confirms this behavior, but it also confirms existing HtmlWebViewSource content that fetched packaged relative resources will break.

⚠️ Warning

None.

💡 Suggestion

None.

Failure-Mode Probing

  • HtmlWebViewSource with <script>fetch('data.json')</script> and null base URL: now fails where it previously succeeded.
  • Real https://appdir/... page using same-origin fetch: remains supported.
  • DOM subresources (<script src>, images, links): remain supported under DenyCors.
  • External hosts matching the old prefix bug: now correctly do not keep/apply local mapping.

Verdict: NEEDS_CHANGES

Confidence: low — platform WebView behavior plus required-check status unavailable.
Summary: The exact-host parsing fix looks correct, but the unresolved LoadHtml compatibility break remains a blocking concern unless explicitly accepted by maintainers as a breaking/security tradeoff.


🛠️ Fix — Analysis & Comparison

Fix Candidates

# Source Approach Test Result Files Changed Notes
1 maui-expert-reviewer Source-aware access mode: Allow only for LoadHtml/null-base; DenyCors for real appdir navigations ⚠️ BLOCKED 2 files Built to test assembly; VSTest missing testhost.dll. Simplest compatibility-preserving alternative.
2 maui-expert-reviewer Serve LoadHtml as a synthetic same-origin https://appdir/__maui_loadhtml/... document ⚠️ BLOCKED 3 files Built after stream fix; VSTest missing testhost.dll. Strong security model but larger URL/history/lifetime risk.
3 maui-expert-reviewer Keep DenyCors, add narrow Origin: null fetch/XHR bridge for LoadHtml appdir requests ⚠️ BLOCKED 3 files Built after content-type fix; VSTest missing testhost.dll. Most targeted but most complex.
PR PR #36603 Exact parsed appdir host detection plus uniform DenyCors mapping at all appdir mapping sites ⚠️ INCONCLUSIVE (Gate) 6 files Original PR; code review found unresolved LoadHtml compatibility regression.

Cross-Pollination

Model Round New Ideas? Details
gpt-5.5 / maui-expert-reviewer 1 Yes Candidate 1: source-aware access mode.
gpt-5.5 / maui-expert-reviewer 2 Yes Candidate 2: synthetic same-origin LoadHtml document after Candidate 1 environment blocker.
gpt-5.5 / maui-expert-reviewer 3 Yes Candidate 3: narrow LoadHtml Origin: null CORS bridge after Candidate 2 tradeoff/failure analysis.
gpt-5.5 / maui-expert-reviewer 4 No The expert reviewer identified the meaningful approach space as exhausted: source-based access kind, origin change, or manual bridge. Further ideas are variants/larger rewrites.

Exhausted: Yes
Selected Fix: None verified — every candidate that reached compilation was blocked before test execution by the same missing testhost.dll environment issue. By code merits, Candidate 1 is the simplest compatibility-preserving alternative; Candidate 2 is the strongest security-preserving alternative but has larger behavior risk. Candidate 3 is not preferred unless maintainers want a narrowly scoped bridge and accept the added complexity.


🏁 Report — Final Recommendation

Comparative Fix Report — PR #36603

Candidates compared

Candidate Approach Regression/test status Ranking impact
pr Exact parsed https://appdir host detection, no userinfo, and uniform DenyCors appdir mapping. PR gate inconclusive overall because the without-fix baseline could not compile, but the with-fix WebViewHandlerTests passed: 22 passed, 0 failed. Best balance of correctness, documented behavior, and implementation risk.
pr-plus-reviewer Same as pr; expert reviewer produced no actionable changes. Same as pr. Equivalent to pr, but ranked below because it is not a distinct improvement.
try-fix-1 Preserve Allow for LoadHtml/data-URI appdir mapping while using DenyCors for real appdir navigations. Blocked by environment/testhost issue; not a regression failure. Compatibility-preserving, but partially backs out the PR's intentional resource-access tightening.
try-fix-2 Serve LoadHtml as a synthetic same-origin https://appdir/__maui_loadhtml/... document. Blocked by environment/testhost issue; not a regression failure. Preserves DenyCors and script-readable resources, but introduces larger behavior risk around synthetic URLs, history, in-memory document lifetime, and handler cleanup.
try-fix-3 Keep DenyCors and add a narrow Origin: null WebResourceRequested bridge for LoadHtml fetch/XHR appdir requests. Blocked by environment/testhost issue; not a regression failure. Most targeted compatibility bridge, but highest implementation complexity and security/path-safety audit burden.

Analysis

The core host-detection fix in pr is sound: using parsed URI components prevents unrelated hosts or userinfo tricks from being treated as local appdir content. The DenyCors change is a deliberate behavior change and is now described in the PR metadata and covered by tests for the key WebView2 access-mode distinctions.

The earlier concern around LoadHtml is real as a compatibility tradeoff: NavigateToString creates an opaque/null-origin document, so script fetch/XHR to https://appdir/... no longer succeeds under DenyCors. However, the current PR explicitly documents that as intentional and provides tests that distinguish DOM subresource loading, same-origin appdir fetch, and cross-origin fetch denial. Given that stated goal, candidates that restore null-origin script-readable access are alternatives to the product decision rather than clear corrections.

try-fix-1 is the simplest compatibility-preserving alternative, but it keeps Allow on the LoadHtml path and therefore weakens the "align resource-access mode" part of the PR. try-fix-2 and try-fix-3 try to preserve both DenyCors and LoadHtml script-readable compatibility, but both add substantially more code and new lifecycle/security surface. None of the try-fix candidates has a passing regression run; they were blocked, not failed, but they also do not outweigh the submitted PR's simpler, tested, and documented behavior.

Winner

Winner: pr

Rationale: The raw PR fix is the simplest implementation that fully matches the documented intended behavior: exact appdir host detection plus a consistent DenyCors local-resource mapping. pr-plus-reviewer is identical because the expert reviewer found no actionable changes, while all try-fix candidates either dilute the intended access-mode change or add larger unverified complexity.


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@kubaflo
kubaflo changed the base branch from main to inflight/current July 27, 2026 08:12
@kubaflo
kubaflo merged commit d314b9c into inflight/current Jul 27, 2026
42 checks passed
@kubaflo
kubaflo deleted the mattleibow-fix-windows-webview-appdir-detection branch July 27, 2026 08:13
@github-actions github-actions Bot added this to the .NET 10 SR10 milestone Jul 27, 2026
kubaflo pushed a commit that referenced this pull request Jul 28, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Jul 29, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Aug 7, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Aug 12, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
@sheiksyedm sheiksyedm modified the milestones: .NET 10 SR10, .NET 10 SR11 Aug 26, 2026
kubaflo pushed a commit that referenced this pull request Aug 27, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 2, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 3, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 3, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 4, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 6, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 7, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 7, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 8, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 8, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…rce-access mode (#36603)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Description

On Windows the standard MAUI `WebView` is backed by `MauiWebView`, which
maps the app's base/installed directory to the fixed local virtual host
`https://appdir/` via
`CoreWebView2.SetVirtualHostNameToFolderMapping(...)`. This PR fixes two
issues in `src/Core/src/Platform/Windows/MauiWebView.cs`.

### Issue 1 — local-host detection compared the raw string instead of
the parsed host

`IsUriWithLocalScheme` decided whether a URL pointed at local `appdir`
content with a raw prefix comparison:

```csharp
uri.StartsWith("https://appdir", StringComparison.OrdinalIgnoreCase)
```

Because this compares the raw string rather than the parsed URL, it also
matched URLs whose real host merely *starts* with those characters:

- `https://appdir.example.com/page.html` → parsed host is
`appdir.example.com`, not `appdir`
- `https://appdir@host.example.com/page.html` → parsed host is
`host.example.com` (`appdir` is the userinfo)

Both were incorrectly treated as local `appdir` content, so the folder
mapping was applied/kept for a host that isn't `appdir`. The same
predicate is reused by the `NavigationStarting` handler, so both
initial-load and navigation-time decisions were affected.

**Fix:** `IsUriWithLocalScheme` now parses the string with
`Uri.TryCreate(..., UriKind.Absolute, out var parsed)` and returns
`true` only when `parsed.Scheme == Uri.UriSchemeHttps`, the URL carries
**no userinfo**, and `parsed.Host` is exactly `appdir` (ordinal,
case-insensitive). It returns `false` when the string can't be parsed as
an absolute URI. `appdir` is an arbitrary placeholder host, so matching
it exactly is the correct behavior.

### Issue 2 — the mapping used a broader resource-access mode than this
host needs

All three mapping call sites passed
`CoreWebView2HostResourceAccessKind.Allow`. For a host that just serves
local app files this is broader than needed. `DenyCors` is the more
appropriate mode for a local file-serving host, and it changes behavior
only in one specific way (details below).

**Fix:** all three `SetVirtualHostNameToFolderMapping` call sites
(`LoadHtml`, `LoadUrl`, `NavigationStarting`) now use `DenyCors`.

## What `DenyCors` changes (and what it doesn't)

Straight from the
[`CoreWebView2HostResourceAccessKind`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2hostresourceaccesskind)
matrix:

| Access from an appdir document | `Allow` (before) | `DenyCors` (now) |
|---|---|---|
| DOM sub-resources (`<img>`, `<script src>`, `<link>`, `<iframe src>`)
| ✅ | ✅ **unchanged** |
| Same-origin `fetch`/XHR from a real `https://appdir/` page (`LoadUrl`)
| ✅ | ✅ **unchanged** |
| Cross-origin `fetch`/XHR to `appdir` (from a null-origin
`NavigateToString`/`LoadHtml` document, or a cross-origin iframe) | ✅ |
⛔ **no longer answered** |

So normal local content — images, CSS, scripts, fonts, iframes, and
same-origin `fetch` on a real `appdir` page — keeps working. The only
behavior change is the last row.

### Intentional behavior change for one `LoadHtml` edge case

`LoadHtml()` uses `NavigateToString`, so that document has a **null
origin** rather than the `https://appdir` origin. A script `fetch`/XHR
to `https://appdir/…` from such a document is cross-origin and is no
longer answered under `DenyCors`. This is intentional. If `LoadHtml`
content specifically needs script-readable local data, the options are
to load a real `https://appdir/` page via `LoadUrl` (same-origin `fetch`
works) or to use `HybridWebView`, which serves app content through
`WebResourceRequested`.

`NavigationStarting` also now correctly calls
`ClearVirtualHostNameToFolderMapping` when navigating to a URL whose
parsed host is not `appdir`.

## API changes

No public API additions — `PublicAPI.Unshipped.txt` is unchanged. The
only new/changed members are two `internal` helpers on the (public)
`MauiWebView`, exposed to the device-tests assembly via
`InternalsVisibleTo` so the host-detection logic can be tested without a
live WebView2:

```csharp
namespace Microsoft.Maui.Platform;

public partial class MauiWebView // : WebView2, IWebViewDelegate
{
    // NEW. The single entry point LoadUrl uses to decide whether a URL is local:
    //   - relative URL         -> true   (later rebased onto https://appdir/)
    //   - https://appdir/...   -> true   (delegates to IsUriWithLocalScheme)
    //   - any other absolute   -> false
    //   - unparseable input    -> false
    internal static bool IsLocalAppDirUrl(string? url);

    // CHANGED. Was a `private static` raw-prefix check; now `internal` (so device
    // tests can call it) and parses the URL: true only when the scheme is https,
    // there is no userinfo, and the host is exactly "appdir" (case-insensitive).
    // Also used by the NavigationStarting handler.
    internal static bool IsUriWithLocalScheme(string? uri);
}
```

## Tests

Added coverage in
`src/Core/tests/DeviceTests/Handlers/WebView/WebViewHandlerTests.Windows.cs`
(Windows-only, since `MauiWebView` is Windows-only). There was
previously no coverage for the host detection or the mapping mode.

**Host-detection (lightweight, pure static calls via the internal
helpers):**
- `IsUriWithLocalScheme`: `https://appdir/…` and `https://APPDIR/…` →
true; `http://appdir/…` → false; `https://appdir.example.com/…` → false;
`https://appdir@host.example.com/…` → false;
`https://user:pass@appdir/…` → false; unrelated host → false; relative →
false.
- `IsLocalAppDirUrl`: relative URLs → local; `https://appdir/…` → local;
subdomain / userinfo / external host → not local.

**Device tests (real WebView2):**
- Local sub-resource (`<script src>`) referenced from `https://appdir/`
still loads.
- **Same-origin `fetch` from a real `https://appdir/` page still
completes** (`appdir-fetch-test.html`).
- **A cross-origin iframe (opaque-origin data: URL) cannot read an
appdir file via `fetch`** (`appdir-iframe-parent.html`), reported back
via `postMessage`.
- `LoadHtml` content (null-origin document) doing a cross-origin `fetch`
of an appdir file does not complete.
- A script `fetch` does **not** raise `NavigationStarting` (confirming
`fetch`/XHR are sub-resource requests, so the mapping mode governs
them).
- Navigating to a non-`appdir` host clears the mapping.

New `Resources/Raw/appdir-*.{html,js}` assets back the device tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7398d63-47a4-4f55-bb87-9f18dab496e0
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 25, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-webview WebView p/0 Current heighest priority issues that we are targeting for a release. platform/windows s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants