From 0602f045e63ef649b5f7e1af5ac9ee23b7d01cea Mon Sep 17 00:00:00 2001 From: Ronny Shapiro Date: Wed, 18 Nov 2026 18:15:40 +0200 Subject: [PATCH 1/3] option to close empty-element tags in html fragments WebClientOptions.setHtmlFragmentSelfClosingTagsAllowed() lets the fragment parser of html pages close a non void element or iframe written as empty-element tag (e.g.

), like up to 5.5.0. Applications that stored asXml() output from before 5.8.0 need to read it back unchanged. The option is disabled by default (like the browsers). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UnykBP1rN49AToLmXitt3s --- src/changes/changes.xml | 6 ++++ .../java/org/htmlunit/WebClientOptions.java | 25 +++++++++++++++ .../parser/neko/HtmlUnitNekoHtmlParser.java | 6 ++-- .../java/org/htmlunit/WebClient8Test.java | 32 +++++++++++++++++++ .../org/htmlunit/WebClientOptionsTest.java | 5 +++ 5 files changed, 72 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 4ab2642c04a..69e69f78757 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -8,6 +8,12 @@ + + New option WebClientOptions.setHtmlFragmentSelfClosingTagsAllowed(); when enabled, the fragment parser + of html pages (e.g. setInnerHtml()) closes a non void element or iframe written as empty-element + tag (e.g. <h3/>) like up to version 5.5.0. This allows applications to read back markup written by + asXml() before 5.8.0. The option is disabled by default (like the browsers). + The private suffixes of the public suffix list (e.g. 'github.io') are handled as public suffixes like in the browsers: cookies for these domains are ignored and the hosts below are different diff --git a/src/main/java/org/htmlunit/WebClientOptions.java b/src/main/java/org/htmlunit/WebClientOptions.java index 0a0977789ef..83454512bc2 100644 --- a/src/main/java/org/htmlunit/WebClientOptions.java +++ b/src/main/java/org/htmlunit/WebClientOptions.java @@ -103,6 +103,8 @@ public class WebClientOptions implements Serializable { private boolean isFetchPolyfillEnabled_; + private boolean htmlFragmentSelfClosingTagsAllowed_; + /** * Sets the SSLContext; if this is set it is used and some other settings are * ignored (protocol, keyStore, keyStorePassword, trustStore, @@ -955,6 +957,29 @@ public boolean isFetchPolyfillEnabled() { return isFetchPolyfillEnabled_; } + /** + * Sets whether the fragment parser of html pages (e.g. {@code setInnerHtml()}) closes a non void element + * or iframe written as empty-element tag (e.g. {@code

}), like up to version 5.5.0. By default the + * trailing slash is ignored like in the browsers. A self-closed script is not affected. + * Enable this to read back markup written by {@code asXml()} before 5.8.0, which wrote empty elements + * like {@code

}. XHTML pages always honor the trailing slash. + * + * @param allowed {@code true} to close a non void element written as empty-element tag + */ + public void setHtmlFragmentSelfClosingTagsAllowed(final boolean allowed) { + htmlFragmentSelfClosingTagsAllowed_ = allowed; + } + + /** + * Returns whether the fragment parser of html pages closes a non void element written as empty-element tag. + * + * @return {@code true} if the fragment parser of html pages closes a non void element written as + * empty-element tag + */ + public boolean isHtmlFragmentSelfClosingTagsAllowed() { + return htmlFragmentSelfClosingTagsAllowed_; + } + /** * Enables/disables Geolocation support. By default, this property is disabled. * diff --git a/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java b/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java index 8497a3645d1..35ffc3c389a 100644 --- a/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java +++ b/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java @@ -105,8 +105,10 @@ public void parseFragment(final WebClient webClient, final DomNode parent, final domBuilder.setInsideSvg(isSvgContext(context)); final boolean xhtml = page instanceof XHtmlPage; - domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS, xhtml); - domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, xhtml); + final boolean selfClosing = xhtml + || htmlPage.getWebClient().getOptions().isHtmlFragmentSelfClosingTagsAllowed(); + domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS, selfClosing); + domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, selfClosing); domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_SCRIPT, xhtml); // build fragment context stack diff --git a/src/test/java/org/htmlunit/WebClient8Test.java b/src/test/java/org/htmlunit/WebClient8Test.java index 7045942d47d..c7daaa4d786 100644 --- a/src/test/java/org/htmlunit/WebClient8Test.java +++ b/src/test/java/org/htmlunit/WebClient8Test.java @@ -176,6 +176,38 @@ public void asXmlEmptySvgElements() throws Exception { } } + /** + * @throws Exception if something goes wrong + */ + @Test + public void parseFragmentIgnoresTrailingSlashOfNonVoidElement() throws Exception { + final String html = DOCTYPE_HTML + "
"; + + try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) { + final HtmlPage page = loadPage(webClient, html, null, URL_FIRST); + final DomElement copy = page.getElementById("copy"); + copy.setInnerHtml("

x

"); + assertEquals("

x

", copy.asXml()); + } + } + + /** + * @throws Exception if something goes wrong + */ + @Test + public void parseFragmentHtmlFragmentSelfClosingTagsAllowed() throws Exception { + final String html = DOCTYPE_HTML + "
"; + + try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) { + webClient.getOptions().setHtmlFragmentSelfClosingTagsAllowed(true); + final HtmlPage page = loadPage(webClient, html, null, URL_FIRST); + final DomElement copy = page.getElementById("copy"); + // markup written by asXml() before 5.8.0 + copy.setInnerHtml("

x

y


", copy.asXml()); + } + } + /** * @throws Exception if something goes wrong */ diff --git a/src/test/java/org/htmlunit/WebClientOptionsTest.java b/src/test/java/org/htmlunit/WebClientOptionsTest.java index 7b50ac14af8..b1b61e0a8f7 100644 --- a/src/test/java/org/htmlunit/WebClientOptionsTest.java +++ b/src/test/java/org/htmlunit/WebClientOptionsTest.java @@ -69,6 +69,8 @@ public void serialization() throws Exception { deserialized.getWebSocketMaxBinaryMessageSize()); assertEquals(original.isFetchPolyfillEnabled(), deserialized.isFetchPolyfillEnabled()); + assertEquals(original.isHtmlFragmentSelfClosingTagsAllowed(), + deserialized.isHtmlFragmentSelfClosingTagsAllowed()); } /** @@ -96,6 +98,7 @@ public void serializationChanged() throws Exception { original.setWebSocketMaxBinaryMessageSize(44); original.setFetchPolyfillEnabled(true); + original.setHtmlFragmentSelfClosingTagsAllowed(true); final byte[] bytes = SerializationUtils.serialize(original); final WebClientOptions deserialized = SerializationUtils.deserialize(bytes); @@ -130,6 +133,8 @@ public void serializationChanged() throws Exception { deserialized.getWebSocketMaxBinaryMessageSize()); assertEquals(original.isFetchPolyfillEnabled(), deserialized.isFetchPolyfillEnabled()); + assertEquals(original.isHtmlFragmentSelfClosingTagsAllowed(), + deserialized.isHtmlFragmentSelfClosingTagsAllowed()); } /** From 4b74d9508bb7e01a13d269c75f36ed130f7a632f Mon Sep 17 00:00:00 2001 From: Ronny Shapiro Date: Wed, 18 Nov 2026 18:24:57 +0200 Subject: [PATCH 2/3] read the option from the webClient parameter Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UnykBP1rN49AToLmXitt3s --- .../org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java b/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java index 35ffc3c389a..36d500806b7 100644 --- a/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java +++ b/src/main/java/org/htmlunit/html/parser/neko/HtmlUnitNekoHtmlParser.java @@ -105,8 +105,7 @@ public void parseFragment(final WebClient webClient, final DomNode parent, final domBuilder.setInsideSvg(isSvgContext(context)); final boolean xhtml = page instanceof XHtmlPage; - final boolean selfClosing = xhtml - || htmlPage.getWebClient().getOptions().isHtmlFragmentSelfClosingTagsAllowed(); + final boolean selfClosing = xhtml || webClient.getOptions().isHtmlFragmentSelfClosingTagsAllowed(); domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS, selfClosing); domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, selfClosing); domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_SCRIPT, xhtml); From 314ddd5fb8df4813d30a1543239e7110ce060946 Mon Sep 17 00:00:00 2001 From: Ronald Brill Date: Mon, 23 Nov 2026 19:43:09 +0100 Subject: [PATCH 3/3] option to allow local file access from remote pages --- src/changes/changes.xml | 63 +++-- .../java/org/htmlunit/WebClientOptions.java | 28 +++ src/main/java/org/htmlunit/html/HtmlPage.java | 5 + .../htmlunit/javascript/host/Location.java | 12 +- .../org/htmlunit/javascript/host/Window.java | 3 +- .../html/LocalResourceAccess3Test.java | 221 ++++++++++++++++++ 6 files changed, 301 insertions(+), 31 deletions(-) create mode 100644 src/test/java/org/htmlunit/html/LocalResourceAccess3Test.java diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d826a9bb41a..453df0d7aee 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -8,6 +8,12 @@ + + New option WebClientOptions.setLocalFileAccessFromRemotePagesAllowed(boolean) (default false). + If enabled, pages that were not loaded from a file are allowed again to load local files (file urls), + to navigate to them and to follow redirects to them, like HtmlUnit did before this release. + Real browsers block this; use the option only if your tests depend on the old behavior. + The files stored by the DownloadingAttachmentHandler are readable for the owner only (by default they are stored in the shared temp directory). The report folder of the DebuggingWebConnection is @@ -29,30 +35,34 @@ core-js: Fix Number.prototype.toPrecision for values below 0.1 that need padding zeros. - The protocol setters (URL, HTMLAnchorElement, HTMLAreaElement, location) follow the rules of the - URL Standard: the scheme is not changed to 'file' if the url has credentials or a port, not - from 'file' if the host is empty and not between special and not special schemes. + INCOMPATIBLE CHANGE: The protocol setters (URL, HTMLAnchorElement, HTMLAreaElement, location) + follow the rules of the URL Standard: the scheme is not changed to 'file' if the url has + credentials or a port, not from 'file' if the host is empty and not between special and not + special schemes. Like the HTML Standard, location.protocol throws a SyntaxError for an invalid scheme and navigates only to http(s) urls (before e.g. 'file:' or 'foo:' was navigated). - URL.href and the href of anchors and areas serialize file urls without host like the URL - Standard ('file:///C:/a', before 'file:/C:/a'). When simulating Firefox, file urls of URL objects - have no host (like Firefox) and setting location.protocol does not reload the page if the url - is not changed. + INCOMPATIBLE CHANGE: URL.href and the href of anchors and areas serialize file urls without host + like the URL Standard ('file:///C:/a', before 'file:/C:/a'). When simulating Firefox, file urls + of URL objects have no host (like Firefox) and setting location.protocol does not reload the page + if the url is not changed. - Like the browsers, a page not loaded from a file is not allowed to load scripts, images, - stylesheets (also @import), workers and importScripts() from local files (file urls); - the load fails like a network error. new Worker() throws a SecurityError (Firefox fires the - error event), importScripts() throws a NetworkError (Firefox a SecurityError). Like Chrome/Edge, - a page loaded from a file is not allowed to start a worker from a local file. + INCOMPATIBLE CHANGE: Like the browsers, a page not loaded from a file is not allowed to load + scripts, images, stylesheets (also @import), workers and importScripts() from local files + (file urls); the load fails like a network error + (see WebClientOptions.setLocalFileAccessFromRemotePagesAllowed(true)). new Worker() throws a + SecurityError (Firefox fires the error event), importScripts() throws a NetworkError (Firefox a + SecurityError). Like Chrome/Edge, a page loaded from a file is not allowed to start a worker from + a local file. - When simulating Firefox, the MIME type of data urls is serialized like the MIME Sniffing Standard - does it (duplicate parameters are ignored, the charset parameter stays in place); like Firefox all - whitespace is removed from the MIME type of base64 data urls. When simulating Chrome/Edge the - parameters are kept like Chrome does it (names and values unchanged, split at every semicolon). + INCOMPATIBLE CHANGE: When simulating Firefox, the MIME type of data urls is serialized like the + MIME Sniffing Standard does it (duplicate parameters are ignored, the charset parameter stays in + place); like Firefox all whitespace is removed from the MIME type of base64 data urls. When + simulating Chrome/Edge the parameters are kept like Chrome does it (names and values unchanged, + split at every semicolon). The ';base64' marker of data urls is case-insensitive and may be surrounded by spaces @@ -72,23 +82,26 @@ location.href does. - Like the browsers, window.open() of a local file (file url) from a page that was not loaded from - a file opens no window and returns null (before an empty window was opened); an existing window - with this name is not navigated and returned (before it was navigated to about:blank); when simulating - Firefox an Error is thrown. + INCOMPATIBLE CHANGE: Like the browsers, window.open() of a local file (file url) from a page that + was not loaded from a file opens no window and returns null (before an empty window was opened); + an existing window with this name is not navigated and returned (before it was navigated to + about:blank); when simulating Firefox an Error is thrown + (see WebClientOptions.setLocalFileAccessFromRemotePagesAllowed(true)). - Like the browsers (Fetch standard), a redirect to an url that is not http(s) (e.g. a local file) - is a network error; before the url was handed over to the web connection. + INCOMPATIBLE CHANGE: Like the browsers (Fetch standard), a redirect to an url that is not http(s) + (e.g. a local file) is a network error; before the url was handed over to the web connection + (redirects to local files: see WebClientOptions.setLocalFileAccessFromRemotePagesAllowed(true)). The href of the base element may be an absolute url with any scheme (e.g. file:); before such an url was appended to the url of the page if this url ends with a slash. - Like in the browsers, a page that was not loaded from a file is no longer able to load a local - file (file url) into a frame or window by setting the location, using window.open(), clicking - a link, submitting a form or a refresh; this was only blocked for the src attribute of frames. + INCOMPATIBLE CHANGE: Like in the browsers, a page that was not loaded from a file is no longer able + to load a local file (file url) into a frame or window by setting the location, using window.open(), + clicking a link, submitting a form or a refresh; this was only blocked for the src attribute of + frames (see WebClientOptions.setLocalFileAccessFromRemotePagesAllowed(true)). csp: when simulating Chrome/Edge, a WebSocket blocked by connect-src fires only the error event diff --git a/src/main/java/org/htmlunit/WebClientOptions.java b/src/main/java/org/htmlunit/WebClientOptions.java index 39529ee16e4..eb0ae0cf01e 100644 --- a/src/main/java/org/htmlunit/WebClientOptions.java +++ b/src/main/java/org/htmlunit/WebClientOptions.java @@ -105,6 +105,8 @@ public class WebClientOptions implements Serializable { private boolean contentSecurityPolicyReportsEnabled_ = true; + private boolean localFileAccessFromRemotePagesAllowed_; + /** * Sets the SSLContext; if this is set it is used and some other settings are * ignored (protocol, keyStore, keyStorePassword, trustStore, @@ -1148,4 +1150,30 @@ public void setContentSecurityPolicyReportsEnabled(final boolean enabled) { public boolean isContentSecurityPolicyReportsEnabled() { return contentSecurityPolicyReportsEnabled_; } + + /** + * Sets whether pages that were not loaded from a local file are allowed to access + * local files (file URLs), default {@code false}. + *

Like the browsers, HtmlUnit blocks e.g. scripts, images, stylesheets, frames, workers + * and navigations to file URLs if the page was not loaded from a file. + * Redirects to file URLs are always blocked (Fetch Standard). + * Enable this only for tests that depend on the old (insecure) behavior of HtmlUnit; + * real browsers will not load these resources.

+ * + * @param allowed whether pages not loaded from a file are allowed to access local files + */ + public void setLocalFileAccessFromRemotePagesAllowed(final boolean allowed) { + localFileAccessFromRemotePagesAllowed_ = allowed; + } + + /** + * Returns whether pages that were not loaded from a local file are allowed to access + * local files (file URLs), default {@code false}. + * + * @return {@code true} if pages not loaded from a file are allowed to access local files + * @see #setLocalFileAccessFromRemotePagesAllowed(boolean) + */ + public boolean isLocalFileAccessFromRemotePagesAllowed() { + return localFileAccessFromRemotePagesAllowed_; + } } diff --git a/src/main/java/org/htmlunit/html/HtmlPage.java b/src/main/java/org/htmlunit/html/HtmlPage.java index 85916603cbb..4cfb3b02af6 100644 --- a/src/main/java/org/htmlunit/html/HtmlPage.java +++ b/src/main/java/org/htmlunit/html/HtmlPage.java @@ -419,11 +419,16 @@ else if (window instanceof TopLevelWindow topLevelWindow) { * Like in the browsers, only pages from a file are allowed to load local resources (file URLs); * about:blank and about:srcdoc documents are judged by the origin of their creator * (see {@link #getOriginUrl()}). + * This check can be disabled with + * {@link org.htmlunit.WebClientOptions#setLocalFileAccessFromRemotePagesAllowed(boolean)}. * * @param url the URL to load * @return {@code false} if the URL is a file URL and this page does not have a file origin */ public boolean isLocalResourceAccessAllowed(final URL url) { + if (getWebClient().getOptions().isLocalFileAccessFromRemotePagesAllowed()) { + return true; + } return UrlUtils.isLocalResourceAccessAllowed(getOriginUrl(), url); } diff --git a/src/main/java/org/htmlunit/javascript/host/Location.java b/src/main/java/org/htmlunit/javascript/host/Location.java index 2720125a396..470effeced3 100644 --- a/src/main/java/org/htmlunit/javascript/host/Location.java +++ b/src/main/java/org/htmlunit/javascript/host/Location.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.LogFactory; import org.htmlunit.BrowserVersion; import org.htmlunit.Page; +import org.htmlunit.WebClient; import org.htmlunit.WebRequest; import org.htmlunit.WebWindow; import org.htmlunit.corejs.javascript.Context; @@ -720,7 +721,8 @@ private static void upgradeInsecureRedirects(final HtmlPage page, final WebWindo */ private void setUrl(final URL url) throws IOException { final WebWindow webWindow = window_.getWebWindow(); - final BrowserVersion browserVersion = webWindow.getWebClient().getBrowserVersion(); + final WebClient webClient = webWindow.getWebClient(); + final BrowserVersion browserVersion = webClient.getBrowserVersion(); URL requestUrl = url; if (webWindow.getEnclosedPage() instanceof HtmlPage page) { @@ -735,11 +737,11 @@ private void setUrl(final URL url) throws IOException { allowed = callingPage.isLocalResourceAccessAllowed(requestUrl); } else { - allowed = UrlUtils.isLocalResourceAccessAllowed(callingWindow.getEnclosedPage().getUrl(), requestUrl); + allowed = webClient.getOptions().isLocalFileAccessFromRemotePagesAllowed() + || UrlUtils.isLocalResourceAccessAllowed(callingWindow.getEnclosedPage().getUrl(), requestUrl); } if (!allowed) { - webWindow.getWebClient().getIncorrectnessListener() - .notify("Not allowed to load local resource: " + requestUrl, this); + webClient.getIncorrectnessListener().notify("Not allowed to load local resource: " + requestUrl, this); return; } @@ -758,7 +760,7 @@ private void setUrl(final URL url) throws IOException { upgradeInsecureRedirects(page, webWindow, webRequest); } - webWindow.getWebClient().getPage(webWindow, webRequest); + webClient.getPage(webWindow, webRequest); } /** diff --git a/src/main/java/org/htmlunit/javascript/host/Window.java b/src/main/java/org/htmlunit/javascript/host/Window.java index f741d33bc58..b351fb851e9 100644 --- a/src/main/java/org/htmlunit/javascript/host/Window.java +++ b/src/main/java/org/htmlunit/javascript/host/Window.java @@ -505,7 +505,8 @@ private static boolean isLocalResourceAccessAllowed(final Page page, final URL u if (page instanceof HtmlPage htmlPage) { return htmlPage.isLocalResourceAccessAllowed(url); } - return UrlUtils.isLocalResourceAccessAllowed(page.getUrl(), url); + return page.getEnclosingWindow().getWebClient().getOptions().isLocalFileAccessFromRemotePagesAllowed() + || UrlUtils.isLocalResourceAccessAllowed(page.getUrl(), url); } private URL makeUrlForOpenWindow(final String urlString) { diff --git a/src/test/java/org/htmlunit/html/LocalResourceAccess3Test.java b/src/test/java/org/htmlunit/html/LocalResourceAccess3Test.java new file mode 100644 index 00000000000..163d8315fe3 --- /dev/null +++ b/src/test/java/org/htmlunit/html/LocalResourceAccess3Test.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2002-2026 Gargoyle Software Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.htmlunit.html; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.htmlunit.CollectingAlertHandler; +import org.htmlunit.MockWebConnection; +import org.htmlunit.Page; +import org.htmlunit.SimpleWebTestCase; +import org.htmlunit.WebClient; +import org.htmlunit.util.MimeType; +import org.htmlunit.util.NameValuePair; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link org.htmlunit.WebClientOptions#setLocalFileAccessFromRemotePagesAllowed(boolean)}. + * The pages are loaded from the (mock) server and refer to local files; this is blocked by default + * (like in the browsers) and allowed if the option is enabled. + * + * @see LocalResourceAccessTest + * @see LocalResourceAccess2Test + * @author Ronald Brill + */ +public class LocalResourceAccess3Test extends SimpleWebTestCase { + + private File dir_; + private String dirUrl_; + + private void createFiles() throws Exception { + dir_ = Files.createTempDirectory("htmlunit-local").toFile().getCanonicalFile(); + dirUrl_ = dir_.toPath().toUri().toString(); + + FileUtils.writeStringToFile(new File(dir_, "local.js"), "var localScript = 'loaded';", UTF_8); + FileUtils.writeStringToFile(new File(dir_, "local.html"), + DOCTYPE_HTML + "local", UTF_8); + } + + /** + * Deletes the temporary directory. + */ + @AfterEach + public void deleteFiles() { + if (dir_ != null) { + FileUtils.deleteQuietly(dir_); + dir_ = null; + } + } + + private WebClient webClient(final boolean allowed) { + final WebClient client = getWebClientWithMockWebConnection(); + client.getOptions().setLocalFileAccessFromRemotePagesAllowed(allowed); + return client; + } + + private List loadScriptPage(final boolean allowed) throws Exception { + createFiles(); + final String html = DOCTYPE_HTML + + "\n" + + "\n" + + "\n" + + ""; + + final WebClient client = webClient(allowed); + final List collectedAlerts = new ArrayList<>(); + client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); + getMockWebConnection().setResponse(URL_FIRST, html); + client.getPage(URL_FIRST); + return collectedAlerts; + } + + /** + * The option is disabled by default. + */ + @Test + public void defaultValue() { + Assertions.assertFalse(getWebClient().getOptions().isLocalFileAccessFromRemotePagesAllowed()); + } + + /** + * A script from a local file is blocked by default. + * + * @throws Exception if the test fails + */ + @Test + public void scriptBlocked() throws Exception { + assertEquals(List.of("undefined"), loadScriptPage(false)); + } + + /** + * A script from a local file is loaded if the option is enabled. + * + * @throws Exception if the test fails + */ + @Test + public void scriptAllowed() throws Exception { + assertEquals(List.of("string"), loadScriptPage(true)); + } + + /** + * A local file is loaded into a frame if the option is enabled. + * + * @throws Exception if the test fails + */ + @Test + public void iframeAllowed() throws Exception { + createFiles(); + final String html = DOCTYPE_HTML + + "\n" + + "\n" + + ""; + + final WebClient client = webClient(true); + getMockWebConnection().setResponse(URL_FIRST, html); + final HtmlPage page = client.getPage(URL_FIRST); + + final Page framePage = page.getFrames().get(0).getEnclosedPage(); + assertEquals("file", framePage.getUrl().getProtocol()); + assertEquals("local", ((HtmlPage) framePage).getTitleText()); + } + + /** + * Setting the location to a local file navigates if the option is enabled. + * + * @throws Exception if the test fails + */ + @Test + public void locationAllowed() throws Exception { + createFiles(); + final String html = DOCTYPE_HTML + + "\n" + + "\n" + + ""; + + final WebClient client = webClient(true); + getMockWebConnection().setResponse(URL_FIRST, html); + client.getPage(URL_FIRST); + client.waitForBackgroundJavaScript(DEFAULT_WAIT_TIME.toMillis()); + + final Page page = client.getCurrentWindow().getEnclosedPage(); + assertEquals("file", page.getUrl().getProtocol()); + } + + /** + * window.open() of a local file opens the window if the option is enabled. + * + * @throws Exception if the test fails + */ + @Test + public void windowOpenAllowed() throws Exception { + createFiles(); + final String html = DOCTYPE_HTML + + "\n" + + "\n" + + ""; + + final WebClient client = webClient(true); + getMockWebConnection().setResponse(URL_FIRST, html); + client.getPage(URL_FIRST); + + final Page page = client.getWebWindowByName("localWindow").getEnclosedPage(); + assertEquals("file", page.getUrl().getProtocol()); + } + + /** + * A redirect to a local file is a network error (Fetch Standard). + * + * @throws Exception if the test fails + */ + @Test + public void redirectBlocked() throws Exception { + createFiles(); + final WebClient client = webClient(false); + redirect(dirUrl_ + "local.html"); + + Assertions.assertThrows(IOException.class, () -> client.getPage(URL_FIRST)); + } + + /** + * The option does not allow redirects to local files; the redirect is still a network error + * (Fetch Standard). + * + * @throws Exception if the test fails + */ + @Test + public void redirectBlockedWithOption() throws Exception { + createFiles(); + final WebClient client = webClient(true); + redirect(dirUrl_ + "local.html"); + + Assertions.assertThrows(IOException.class, () -> client.getPage(URL_FIRST)); + } + + private void redirect(final String target) { + final MockWebConnection conn = getMockWebConnection(); + final List headers = new ArrayList<>(); + headers.add(new NameValuePair("Location", target)); + conn.setResponse(URL_FIRST, "", 302, "Found", MimeType.TEXT_HTML, headers); + } +}