Skip to content

Truly independent web browser

LibWebView+Hub+UI: Grant the folder of a file the user opens

Shannon Booth8c51abf4fa07
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index d47ee451c0f..ad2ecd2051f 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -817,6 +817,14 @@ ErrorOr<void> Application::create_profile([[maybe_unused]] Optional<StringView>
m_profile = TRY(Profile::create(profile_selection, profile_roots));
#endif
+ auto const& paths = m_profile->paths();
+ auto root_for_tests = m_web_content_options.is_test_mode == IsTestMode::Yes ? m_browser_options.local_file_root_for_tests : Optional<ByteString> {};
+ m_local_file_grant_policy = LocalFileGrantPolicy {
+ Core::StandardPaths::home_directory(),
+ { paths.config, paths.data, paths.cache, paths.runtime, paths.identity, m_instance_data_directory },
+ move(root_for_tests),
+ };
+
return {};
}
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 63537b8ea3f..628c5acfc64 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -53,6 +53,7 @@
#include <LibWebView/ExternalURLHandler.h>
#include <LibWebView/FileDownloader.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
#include <LibWebView/MediaSessionCoordinator.h>
#include <LibWebView/Options.h>
#include <LibWebView/PlatformFeatureDecisions.h>
@@ -96,6 +97,7 @@ public:
static Settings& settings() { return *the().m_settings; }
static Profile const& profile() { return *the().m_profile; }
+ static LocalFileGrantPolicy const& local_file_grant_policy() { return the().m_local_file_grant_policy; }
BrowserProcess& browser_process() { return *m_browser_process; }
bool should_exit_after_profile_coordination() const { return m_should_exit_after_profile_coordination; }
// Whether the process exits because a browser is running for the profile, but does not take what we were asked to
@@ -610,6 +612,7 @@ private:
static Application* s_the;
Optional<Profile> m_profile;
+ LocalFileGrantPolicy m_local_file_grant_policy;
OwnPtr<Settings> m_settings;
OwnPtr<BrowserProcess> m_browser_process;
bool m_should_exit_after_profile_coordination { false };
diff --git a/Libraries/LibWebView/BlobURLStore.cpp b/Libraries/LibWebView/BlobURLStore.cpp
index 303a30aa009..9964922d2a6 100644
--- a/Libraries/LibWebView/BlobURLStore.cpp
+++ b/Libraries/LibWebView/BlobURLStore.cpp
@@ -25,7 +25,7 @@ static Optional<URL::BlobURLEntry::Token> token_of(Web::FileAPI::SerializedBlobU
}
// https://w3c.github.io/FileAPI/#add-an-entry
-URL::BlobURLEntry::Token BlobURLStore::add_entry(Utf16String url, Web::FileAPI::SerializedBlobURLEntry entry, BlobURLEntryOwner added_by, AddedByLocalFileContent added_by_local_file_content)
+URL::BlobURLEntry::Token BlobURLStore::add_entry(Utf16String url, Web::FileAPI::SerializedBlobURLEntry entry, BlobURLEntryOwner added_by, Optional<LocalFileRoot> root_of_adder)
{
// NB: Blob URLs are random, so one that is already here came from a different process. Leave it alone.
if (m_entries.contains(url))
@@ -39,7 +39,7 @@ URL::BlobURLEntry::Token BlobURLStore::add_entry(Utf16String url, Web::FileAPI::
m_entry_urls_by_token.set(token, url);
}
- m_entries.set(move(url), Entry { move(entry), move(added_by), added_by_local_file_content, false, 0 });
+ m_entries.set(move(url), Entry { move(entry), move(added_by), move(root_of_adder), false, 0 });
return token;
}
@@ -162,14 +162,12 @@ Optional<Web::FileAPI::SerializedBlobURLEntry> BlobURLStore::resolve(Utf16String
return entry->entry;
}
-bool BlobURLStore::is_entry_of_local_file_content(Utf16String const& url, URL::Origin const& origin) const
+Optional<LocalFileRoot> BlobURLStore::local_file_root_of_entry(Utf16String const& url, URL::Origin const& origin) const
{
auto entry = m_entries.get(url);
- return entry.has_value()
- && !entry->revoked
- && entry->added_by_local_file_content == AddedByLocalFileContent::Yes
- && entry->entry.origin.is_file_origin()
- && entry->entry.origin.is_same_origin(origin);
+ if (!entry.has_value() || entry->revoked || !entry->entry.origin.is_file_origin() || !entry->entry.origin.is_same_origin(origin))
+ return {};
+ return entry->root_of_adder;
}
BlobURLHandle::BlobURLHandle(BlobURLStore& store, URL::BlobURLEntry::Token token)
diff --git a/Libraries/LibWebView/BlobURLStore.h b/Libraries/LibWebView/BlobURLStore.h
index 2b20a73d47d..bbdd8ff97d9 100644
--- a/Libraries/LibWebView/BlobURLStore.h
+++ b/Libraries/LibWebView/BlobURLStore.h
@@ -15,30 +15,26 @@
#include <LibWebCommon/FileAPI/SerializedBlobURLEntry.h>
#include <LibWebView/Export.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
namespace WebView {
using BlobURLEntryOwner = Variant<WeakPtr<WebContentClient>, WeakPtr<WebWorkerClient>>;
-enum class AddedByLocalFileContent : u8 {
- No,
- Yes,
-};
-
// https://w3c.github.io/FileAPI/#BlobURLStore
class WEBVIEW_API BlobURLStore : public Weakable<BlobURLStore> {
public:
AK_ALLOC_WITH_KMALLOC;
- URL::BlobURLEntry::Token add_entry(Utf16String url, Web::FileAPI::SerializedBlobURLEntry, BlobURLEntryOwner added_by, AddedByLocalFileContent = AddedByLocalFileContent::No);
+ URL::BlobURLEntry::Token add_entry(Utf16String url, Web::FileAPI::SerializedBlobURLEntry, BlobURLEntryOwner added_by, Optional<LocalFileRoot> root_of_adder = {});
void remove_entries(Vector<Utf16String> const& urls, URL::Origin const& environment_origin, BlobURLEntryOwner const& removed_by);
void remove_entries_added_by(BlobURLEntryOwner const&);
void remove_entries_added_by(Vector<Utf16String> const& urls, BlobURLEntryOwner const&);
Optional<Web::FileAPI::SerializedBlobURLEntry> resolve(Utf16String const& url, Optional<URL::BlobURLEntry::Token>) const;
- // Whether url names an entry that local file content added, for documents of the entry's origin.
- bool is_entry_of_local_file_content(Utf16String const& url, URL::Origin const&) const;
+ // The local file root of the entry's creator, if the entry belongs to the given origin.
+ Optional<LocalFileRoot> local_file_root_of_entry(Utf16String const& url, URL::Origin const&) const;
// A revoked entry outlives its revocation for as long as handles are held on its token, and is dropped with the
// last of them. Session history holds none, so a blob URL cannot be traversed back to once it is revoked.
@@ -49,7 +45,7 @@ private:
struct Entry {
Web::FileAPI::SerializedBlobURLEntry entry;
BlobURLEntryOwner added_by;
- AddedByLocalFileContent added_by_local_file_content { AddedByLocalFileContent::No };
+ Optional<LocalFileRoot> root_of_adder;
bool revoked { false };
size_t handles { 0 };
};
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 4169a352f8c..c90782e5457 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -44,6 +44,7 @@ set(SOURCES
ImageDecoderControlClient.cpp
ImageDecoderManager.cpp
LingeringIndicator.cpp
+ LocalFileRoot.cpp
MediaSessionCoordinator.cpp
NavigationLoader.cpp
Omnibox.cpp
diff --git a/Libraries/LibWebView/CanonicalDocument.cpp b/Libraries/LibWebView/CanonicalDocument.cpp
index c463cd5505f..a988ea604d1 100644
--- a/Libraries/LibWebView/CanonicalDocument.cpp
+++ b/Libraries/LibWebView/CanonicalDocument.cpp
@@ -75,7 +75,7 @@ bool CanonicalDocument::is_top_level() const
bool CanonicalDocument::may_share_a_process_with_tabs_of_its_origin() const
{
- if (!is_top_level() || m_origin.is_opaque() || m_web_ui_host.has_value() || m_is_local_file_content)
+ if (!is_top_level() || m_origin.is_opaque() || m_web_ui_host.has_value() || is_local_file_content())
return false;
auto const& scheme = m_origin.scheme();
@@ -103,15 +103,18 @@ void CanonicalDocument::set_host(RefPtr<WebContentPage> host)
}
}
-// NB: Only a navigation the UI process admitted to a file: URL creates a document from one. A blob: URL entry local file
-// content added carries that content's origin, as a document created from it does. The entry can be revoked once
-// the document exists, so this is settled when the document is populated, before a process is chosen to host it.
-void CanonicalDocument::determine_whether_it_is_local_file_content(BlobURLStore const* blob_url_store)
+// NB: Only a navigation the UI process admitted to a file: URL creates a document from one, and the document takes the
+// root the UI process used to read the file. A blob: URL entry local file content added carries that content's origin, as a document
+// created from it does. The entry can be revoked once the document exists, so this is settled when the document is
+// populated, before a process is chosen to host it.
+void CanonicalDocument::determine_whether_it_is_local_file_content(BlobURLStore const* blob_url_store, Optional<LocalFileRoot> root_of_read_file)
{
- m_is_local_file_content = m_creation_url.scheme() == "file"sv
- || (m_creation_url.scheme() == "blob"sv
- && blob_url_store
- && blob_url_store->is_entry_of_local_file_content(Utf16String::from_utf8(m_creation_url.serialize(URL::ExcludeFragment::Yes)), m_origin));
+ if (m_creation_url.scheme() == "file"sv)
+ m_local_file_root = move(root_of_read_file);
+ else if (m_creation_url.scheme() == "blob"sv && blob_url_store)
+ m_local_file_root = blob_url_store->local_file_root_of_entry(Utf16String::from_utf8(m_creation_url.serialize(URL::ExcludeFragment::Yes)), m_origin);
+ else
+ m_local_file_root.clear();
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#make-active
diff --git a/Libraries/LibWebView/CanonicalDocument.h b/Libraries/LibWebView/CanonicalDocument.h
index 94a0c372776..e1f0db3ecdb 100644
--- a/Libraries/LibWebView/CanonicalDocument.h
+++ b/Libraries/LibWebView/CanonicalDocument.h
@@ -19,6 +19,7 @@
#include <LibWebCommon/PermissionsPolicy/PermissionsPolicy.h>
#include <LibWebView/Export.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
namespace WebView {
@@ -99,10 +100,11 @@ public:
// document may not. Other opener policies only keep cross-origin windows away.
bool may_share_a_process_with_tabs_of_its_origin() const;
- // Whether this is local file content, whose process may read local files: a document created from a file: URL, or
- // from a blob: URL whose entry local file content added.
- bool is_local_file_content() const { return m_is_local_file_content; }
- void determine_whether_it_is_local_file_content(BlobURLStore const*);
+ // Whether this is local file content, whose process may read local files under its root: a document created from a
+ // file: URL that the UI process read, or from a blob: URL that local file content added.
+ bool is_local_file_content() const { return m_local_file_root.has_value(); }
+ Optional<LocalFileRoot> const& local_file_root() const { return m_local_file_root; }
+ void determine_whether_it_is_local_file_content(BlobURLStore const*, Optional<LocalFileRoot> root_of_read_file);
// The host of the WebUI the document displays, if it was created from the about: URL of a page with a channel to
// the UI process.
@@ -125,7 +127,7 @@ private:
Web::PermissionsPolicy::PermissionsPolicy m_permissions_policy { Web::PermissionsPolicy::PermissionsPolicy::empty_permissions_policy() };
bool m_completely_loaded { false };
u32 m_unload_counter { 0 };
- bool m_is_local_file_content { false };
+ Optional<LocalFileRoot> m_local_file_root;
Optional<String> m_web_ui_host;
RefPtr<WebContentPage> m_host;
};
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index a3c3ad9cf33..ca1fd025f19 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -183,7 +183,7 @@ Web::HTML::PreparedNavigationDescriptor CanonicalNavigable::prepare_navigation(U
}
// Continue the navigate algorithm at step 9 with the values prepared by steps 1-7.
-void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescriptor navigation, RefPtr<WebContentPage> source_page)
+void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescriptor navigation, RefPtr<WebContentPage> source_page, LocalFileAccess local_file_access)
{
auto& traversable = top_level_traversable();
auto const& url = navigation.url;
@@ -339,6 +339,7 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto
.state = CanonicalNavigation::CheckingIfUnloadingIsCanceled { move(start_request) },
.page = worker,
.source_page = move(source_page),
+ .local_file_access = move(local_file_access),
});
worker->async_set_ongoing_navigation(id(), navigation_id);
worker->begin_navigation_unload_check(*this, navigation_id);
@@ -892,6 +893,26 @@ static Optional<String> origin_of_sandboxed_document(CanonicalNavigable const& n
return {};
}
+// The inherited root is settled before a process is chosen, so that reusing a process can't combine roots.
+static Optional<LocalFileRoot> local_file_root_to_host(CanonicalNavigable const& navigable, CanonicalDocument const& document)
+{
+ if (document.is_local_file_content())
+ return document.local_file_root();
+ auto const& url = document.creation_url();
+ if (!document.origin().is_file_origin() && !Web::HTML::url_matches_about_srcdoc(url) && url.scheme() != "data"sv)
+ return {};
+ for (auto const* ancestor = navigable.parent(); ancestor; ancestor = ancestor->parent()) {
+ if (auto const& root = ancestor->active_document().local_file_root(); root.has_value())
+ return root;
+ }
+ return {};
+}
+
+static bool may_read_local_files_under(WebContentClient const& process, Optional<LocalFileRoot> const& root)
+{
+ return !root.has_value() || process.local_file_roots() == Vector { *root };
+}
+
static RefPtr<WebContentClient> lowest_process_hosting_only_tabs_like(CanonicalDocument const& document, BrowsingSession const& session)
{
RefPtr<WebContentClient> process;
@@ -980,16 +1001,17 @@ RefPtr<WebContentClient> CanonicalNavigable::process_to_host(CanonicalDocument c
// WebUI documents too, and that process may then read local files or speak for the WebUI for as long as it lives.
if (Application::the().tab_processes() == TabProcesses::PerTabWithoutSiteIsolation)
return process;
- auto process_has_hosted_local_file_content = process && process->has_hosted_local_file_content();
+ auto process_has_hosted_local_file_content = process && process->may_read_local_files();
auto process_has_hosted_web_ui = process && process->hosted_web_ui().has_value();
if (document.web_ui_host().has_value())
return process && process->hosted_web_ui() == document.web_ui_host() ? process : nullptr;
+ auto root = local_file_root_to_host(*this, document);
if (document.is_local_file_content())
- return process_has_hosted_local_file_content ? process : nullptr;
+ return process && may_read_local_files_under(*process, root) ? process : nullptr;
if (!process_has_hosted_local_file_content && !process_has_hosted_web_ui)
return process;
- if (process_has_hosted_local_file_content && document.origin().is_file_origin())
+ if (process_has_hosted_local_file_content && document.origin().is_file_origin() && may_read_local_files_under(*process, root))
return process;
// An agent runs in one process, and one the process hosts was let in with the documents it has there.
@@ -1003,8 +1025,10 @@ RefPtr<WebContentClient> CanonicalNavigable::process_to_host(CanonicalDocument c
return process;
auto is_made_from_what_its_initiator_holds = Web::HTML::url_matches_about_srcdoc(url) || url.scheme() == "data"sv;
- if (process_has_hosted_local_file_content && is_made_from_what_its_initiator_holds && initiator_origin.has_value() && initiator_origin->is_file_origin())
+ if (process_has_hosted_local_file_content && is_made_from_what_its_initiator_holds && initiator_origin.has_value() && initiator_origin->is_file_origin()
+ && may_read_local_files_under(*process, root)) {
return process;
+ }
return nullptr;
}
@@ -1015,12 +1039,14 @@ ErrorOr<NonnullRefPtr<WebContentPage>> CanonicalNavigable::obtain_page_to_host(C
if (auto origin = origin_of_sandboxed_document(*this, document); origin.has_value()) {
document.browsing_context().top_level_browsing_context().group()->set_process_hosting_sandboxed_documents_of_origin(*origin, page->client());
// NB: A sandboxed srcdoc or data: URL iframe of local file content loads files as that content can.
- if (*origin == serialized_file_origin)
- page->client().set_has_hosted_local_file_content();
+ if (*origin == serialized_file_origin) {
+ if (auto root = local_file_root_to_host(*this, document); root.has_value())
+ TRY(page->client().add_local_file_root(root.release_value()));
+ }
}
}
if (document.is_local_file_content())
- page->client().set_has_hosted_local_file_content();
+ TRY(page->client().add_local_file_root(*document.local_file_root()));
if (auto const& web_ui_host = document.web_ui_host(); web_ui_host.has_value()) {
page->client().set_hosted_web_ui(*web_ui_host);
// NB: The page took the view's preferences before it hosted the WebUI, so it now takes the interface theme.
@@ -1090,7 +1116,7 @@ ErrorOr<CanonicalNavigable::PageToPopulateDocument> CanonicalNavigable::obtain_p
response_document->document_id = Application::the().allocate_ui_process_cross_process_id();
auto document = create_and_initialize_a_document(*response_document);
loader.set_document(*document, *this);
- populate_document(document_state, document, loader.result().inline_content_origin);
+ populate_document(document_state, document, loader.result().inline_content_origin, loader.local_file_root());
// A document created for inline content stands in for the resource the process that fetched it could not load; that
// process hosts it.
@@ -1126,11 +1152,11 @@ RefPtr<CanonicalDocument> CanonicalNavigable::document_with_id(Web::HTML::CrossP
}
// A document state that is not a navigation's is a history job's, which the navigable holds while the job runs.
-void CanonicalNavigable::populate_document(NonnullRefPtr<CanonicalDocumentState> document_state, NonnullRefPtr<CanonicalDocument> document, Optional<URL::Origin> inline_content_origin)
+void CanonicalNavigable::populate_document(NonnullRefPtr<CanonicalDocumentState> document_state, NonnullRefPtr<CanonicalDocument> document, Optional<URL::Origin> inline_content_origin, Optional<LocalFileRoot> root_of_read_file)
{
- document->determine_whether_it_is_local_file_content(blob_url_store());
+ document->determine_whether_it_is_local_file_content(blob_url_store(), move(root_of_read_file));
if (document->is_local_file_content())
- document_state->held_local_file_content = true;
+ document_state->local_file_root = document->local_file_root();
abandon_populated_document(document_state);
auto is_for_navigation = any_of(m_navigations, [&](auto const& navigation) {
return navigation->history_entry && navigation->history_entry->document_state == document_state;
@@ -1146,16 +1172,17 @@ void CanonicalNavigable::populate_document(NonnullRefPtr<CanonicalDocumentState>
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-to-a-javascript:-url
// NB: newDocument's URL is the active document's, as the process hosting both reports it. Whatever URL it reports,
// newDocument holds no local file content and displays no WebUI unless the active document does, as its contents
-// come from that process.
+// come from that process. Its local file content has the active document's root.
void CanonicalNavigable::populate_document_for_javascript_url(CanonicalNavigation& navigation, NonnullRefPtr<CanonicalSessionHistoryEntry> history_entry, NonnullRefPtr<CanonicalDocument> document)
{
- document->determine_whether_it_is_local_file_content(blob_url_store());
- if (document->is_local_file_content() && !active_document().is_local_file_content())
+ auto const& root = active_document().local_file_root();
+ document->determine_whether_it_is_local_file_content(blob_url_store(), root);
+ if (document->is_local_file_content() && document->local_file_root() != root)
return;
if (document->web_ui_host().has_value() && document->web_ui_host() != active_document().web_ui_host())
return;
navigation.history_entry = move(history_entry);
- populate_document(navigation.history_entry->document_state, move(document));
+ populate_document(navigation.history_entry->document_state, move(document), {}, root);
}
// The process hosting a document populated for the navigable created it with an origin other than its navigation
diff --git a/Libraries/LibWebView/CanonicalNavigable.h b/Libraries/LibWebView/CanonicalNavigable.h
index 305fb911977..7ac8fd85078 100644
--- a/Libraries/LibWebView/CanonicalNavigable.h
+++ b/Libraries/LibWebView/CanonicalNavigable.h
@@ -95,7 +95,7 @@ public:
Utf16String const& target_name() const;
RefPtr<CanonicalDocument> document_with_id(Web::HTML::CrossProcessId) const;
- void populate_document(NonnullRefPtr<CanonicalDocumentState>, NonnullRefPtr<CanonicalDocument>, Optional<URL::Origin> inline_content_origin = {});
+ void populate_document(NonnullRefPtr<CanonicalDocumentState>, NonnullRefPtr<CanonicalDocument>, Optional<URL::Origin> inline_content_origin = {}, Optional<LocalFileRoot> root_of_read_file = {});
// Populates nothing for a document that would hold access the active document lacks.
void populate_document_for_javascript_url(CanonicalNavigation&, NonnullRefPtr<CanonicalSessionHistoryEntry>, NonnullRefPtr<CanonicalDocument>);
void did_create_populated_document_with_an_origin_of_its_own(WebContentPage const& host, Web::HTML::CrossProcessId document_id, Web::HTML::PopulatedDocumentOrigin, Web::HTML::EnvironmentId const& environment_id);
@@ -121,7 +121,7 @@ public:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
void navigate(URL::URL, Web::HTML::DocumentResource = {}, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);
Web::HTML::PreparedNavigationDescriptor prepare_navigation(URL::URL, Web::HTML::DocumentResource = {}, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);
- void begin_navigation(Web::HTML::PreparedNavigationDescriptor, RefPtr<WebContentPage> source_page = {});
+ void begin_navigation(Web::HTML::PreparedNavigationDescriptor, RefPtr<WebContentPage> source_page = {}, LocalFileAccess = {});
CanonicalBrowsingContext::BrowsingContextAndDocument obtain_a_browsing_context_to_use_for_a_navigation_response(NavigationLoader::ResponseDocument const&);
NonnullRefPtr<CanonicalDocument> create_and_initialize_a_document(NavigationLoader::ResponseDocument const&);
diff --git a/Libraries/LibWebView/CanonicalNavigation.h b/Libraries/LibWebView/CanonicalNavigation.h
index 6fbaa08cfc8..bf6288e7df2 100644
--- a/Libraries/LibWebView/CanonicalNavigation.h
+++ b/Libraries/LibWebView/CanonicalNavigation.h
@@ -77,6 +77,7 @@ public:
RefPtr<WebContentPage> page {};
RefPtr<CanonicalSessionHistoryEntry> history_entry {};
RefPtr<WebContentPage> source_page {};
+ LocalFileAccess local_file_access {};
};
static NonnullRefPtr<CanonicalNavigation> create(Start start)
{
@@ -98,6 +99,8 @@ public:
BlobURLHandle blob_url;
// The page hosting the source document, as checked when another page requested the navigation.
RefPtr<WebContentPage> source_page {};
+ // Kept for a retry, which reads only what this navigation could.
+ LocalFileAccess local_file_access;
RefPtr<WebContentPage> worker() const;
RefPtr<WebContentPage> host() const;
@@ -116,6 +119,7 @@ private:
, page(move(start.page))
, history_entry(move(start.history_entry))
, source_page(move(start.source_page))
+ , local_file_access(move(start.local_file_access))
{
}
};
diff --git a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h b/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
index 869464e6f95..ea4b35f1ad8 100644
--- a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
+++ b/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
@@ -75,9 +75,9 @@ public:
Utf16String navigable_target_name;
Vector<CanonicalNestedHistory> nested_histories;
- // Whether the UI process populated local file content for this document state. Only then does the UI process read
- // the file its entry names when populating it again: a process reports an entry's URL, but not this.
- bool held_local_file_content { false };
+ // Saved root used when repopulating this document state.
+ // The renderer can report entry URLs, but cannot supply this root.
+ Optional<LocalFileRoot> local_file_root;
private:
explicit CanonicalDocumentState(Web::HTML::CrossProcessId);
diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cpp
index 01b560e1911..6a63a9842da 100644
--- a/Libraries/LibWebView/CanonicalTraversable.cpp
+++ b/Libraries/LibWebView/CanonicalTraversable.cpp
@@ -980,7 +980,12 @@ void CanonicalTraversable::reconstruct_the_history_to_step(i32 step)
ErrorOr<URL::URL> CanonicalTraversable::restore_session_history_from_ui_snapshot(SessionHistorySnapshot snapshot)
{
- TRY(m_session_history.restore_from_ui_snapshot(move(snapshot.entries), move(snapshot.used_steps), snapshot.current_used_step_index, [] { return Application::the().allocate_ui_process_cross_process_id(); }, snapshot.document_states_holding_local_file_content));
+ Vector<DocumentStateLocalFileRoot> local_file_roots;
+ for (auto& [document_state_id, root] : snapshot.local_file_roots_of_document_states) {
+ if (auto restored_root = Application::local_file_grant_policy().restore(move(root)); restored_root.has_value())
+ local_file_roots.append({ document_state_id, restored_root.release_value() });
+ }
+ TRY(m_session_history.restore_from_ui_snapshot(move(snapshot.entries), move(snapshot.used_steps), snapshot.current_used_step_index, [] { return Application::the().allocate_ui_process_cross_process_id(); }, local_file_roots));
session_history_changed();
return m_session_history.current_entry().url;
@@ -1409,13 +1414,13 @@ void CanonicalTraversable::did_receive_changing_navigable_history_job_reached_po
.user_involvement = operation->algorithm->user_involvement(),
.navigation_id = finalized_navigation_id(*operation, navigable_id).value_or(Utf16String {}),
};
- // NB: The process running the job need not have hosted local file content. The UI process reads the local file of
- // an entry whose document state held local file content for the process creating the document, as it does that
- // of any entry for a process running the job that may read local files itself.
- auto may_read_local_file = changing_navigable->target_entry->document_state->held_local_file_content || source_page.client().may_read_local_files()
- ? NavigationLoader::MayReadLocalFile::Yes
- : NavigationLoader::MayReadLocalFile::No;
- auto loader = NavigationLoader::create(move(request), may_read_local_file);
+ // NB: The process running the job need not have hosted local file content. The UI process reads the entry's file
+ // for the process creating the document, with the root saved with the document state, or else with the roots
+ // of the process running the job.
+ auto local_file_access = source_page.client().local_file_access();
+ if (auto const& root = changing_navigable->target_entry->document_state->local_file_root; root.has_value())
+ local_file_access = Vector { *root };
+ auto loader = NavigationLoader::create(move(request), move(local_file_access));
changing_navigable->population = ChangingNavigable::CreatingNavigationParams { loader };
source_page.owe_reply({ OwedReply::Kind::ChangingJob, operation_id, navigable_id });
source_page.async_create_history_navigation_params(operation_id, loader->request(), allow_POST);
diff --git a/Libraries/LibWebView/LocalFileRoot.cpp b/Libraries/LibWebView/LocalFileRoot.cpp
new file mode 100644
index 00000000000..0e23465ac37
--- /dev/null
+++ b/Libraries/LibWebView/LocalFileRoot.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <AK/LexicalPath.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibWebView/LocalFileRoot.h>
+
+namespace WebView {
+
+// NB: Every path here is canonical, and so absolute: is_child_of() takes any relative path to be under a directory.
+bool LocalFileRoot::covers(StringView canonical_path) const
+{
+ if (scope == Scope::File)
+ return canonical_path == path;
+ return LexicalPath { canonical_path }.is_child_of(LexicalPath { path });
+}
+
+static ByteString resolved_directory(ByteString directory)
+{
+ if (auto resolved = FileSystem::real_path(directory); !resolved.is_error())
+ return resolved.release_value();
+ return LexicalPath::canonicalized_path(move(directory));
+}
+
+LocalFileGrantPolicy::LocalFileGrantPolicy(ByteString home_directory, Vector<ByteString> profile_directories, Optional<ByteString> root_for_tests)
+ : m_home_directory(resolved_directory(move(home_directory)))
+{
+ for (auto& directory : profile_directories)
+ m_profile_directories.append(resolved_directory(move(directory)));
+ if (root_for_tests.has_value())
+ m_root_for_tests = resolved_directory(root_for_tests.release_value());
+}
+
+bool LocalFileGrantPolicy::may_grant_directory(StringView canonical_directory) const
+{
+ LexicalPath directory { canonical_directory };
+ if (directory.parts_view().is_empty() || LexicalPath { m_home_directory }.is_child_of(directory))
+ return false;
+ return !any_of(m_profile_directories, [&](auto const& profile_directory) {
+ LexicalPath protected_directory { profile_directory };
+ return protected_directory.is_child_of(directory) || directory.is_child_of(protected_directory);
+ });
+}
+
+LocalFileRoot LocalFileGrantPolicy::root_for_opened_file(ByteString const& canonical_file_path) const
+{
+ if (m_root_for_tests.has_value() && LexicalPath { canonical_file_path }.is_child_of(LexicalPath { *m_root_for_tests }))
+ return { *m_root_for_tests, LocalFileRoot::Scope::Directory };
+
+ auto directory = LexicalPath::dirname(canonical_file_path);
+ if (may_grant_directory(directory))
+ return { move(directory), LocalFileRoot::Scope::Directory };
+ return { canonical_file_path, LocalFileRoot::Scope::File };
+}
+
+Optional<LocalFileRoot> LocalFileGrantPolicy::restore(LocalFileRoot root) const
+{
+ if (root.scope == LocalFileRoot::Scope::File || root.path == m_root_for_tests || may_grant_directory(root.path))
+ return root;
+ return {};
+}
+
+}
diff --git a/Libraries/LibWebView/LocalFileRoot.h b/Libraries/LibWebView/LocalFileRoot.h
new file mode 100644
index 00000000000..e6b263691fe
--- /dev/null
+++ b/Libraries/LibWebView/LocalFileRoot.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteString.h>
+#include <AK/Optional.h>
+#include <AK/StringView.h>
+#include <AK/Variant.h>
+#include <AK/Vector.h>
+#include <LibWebView/Export.h>
+
+namespace WebView {
+
+struct WEBVIEW_API LocalFileRoot {
+ enum class Scope : u8 {
+ Directory,
+ File,
+ };
+
+ ByteString path;
+ Scope scope { Scope::Directory };
+
+ bool covers(StringView canonical_path) const;
+ bool operator==(LocalFileRoot const&) const = default;
+};
+
+struct UserSelectedLocalFile { };
+
+// What a navigation to a file: URL may read: nothing, the file the user chose, or what one of the roots covers.
+using LocalFileAccess = Variant<Empty, UserSelectedLocalFile, Vector<LocalFileRoot>>;
+
+// A file the user opens grants its folder, or the file alone when the folder is too wide: a root never contains a
+// protected directory (the profile's, or the home directory), nor is it inside one other than home.
+class WEBVIEW_API LocalFileGrantPolicy {
+public:
+ LocalFileGrantPolicy() = default;
+ LocalFileGrantPolicy(ByteString home_directory, Vector<ByteString> profile_directories, Optional<ByteString> root_for_tests = {});
+
+ LocalFileRoot root_for_opened_file(ByteString const& canonical_file_path) const;
+
+ // A saved root, if it's still allowed. A disallowed directory root is dropped, since narrowing it to a file root
+ // wouldn't keep access to its contents.
+ Optional<LocalFileRoot> restore(LocalFileRoot) const;
+
+private:
+ bool may_grant_directory(StringView canonical_directory) const;
+
+ ByteString m_home_directory;
+ Vector<ByteString> m_profile_directories;
+ Optional<ByteString> m_root_for_tests;
+};
+
+}
diff --git a/Libraries/LibWebView/NavigationLoader.cpp b/Libraries/LibWebView/NavigationLoader.cpp
index e8c2ab27b32..af942c14705 100644
--- a/Libraries/LibWebView/NavigationLoader.cpp
+++ b/Libraries/LibWebView/NavigationLoader.cpp
@@ -440,22 +440,26 @@ void NavigationLoader::acquire_response_body(WebContentClient const& population_
}
// NB: The process that fetched a navigation's response to a file: URL ran the navigation's population steps for a
-// source document that can be web content, so it did not read the file. The UI process reads the file the admitted
-// URL names, off its main thread, and the process creating the document, which may read local files, takes it.
+// source document that can be web content, so it did not read the file. The UI process reads it off its main
+// thread, with the navigation's local file access, and hands its contents to the process creating the document.
void NavigationLoader::read_local_file_for_response()
{
- if (m_may_read_local_file == MayReadLocalFile::No || m_requested_url.scheme() != "file"sv) {
+ if (m_local_file_access.has<Empty>() || m_requested_url.scheme() != "file"sv) {
did_read_local_file_for_response(Error::from_errno(EACCES));
return;
}
- Threading::ThreadPool::the().submit([weak_this = make_weak_ptr(), path = m_requested_url.file_path(), event_loop = Core::EventLoop::current_weak()] mutable {
+ Threading::ThreadPool::the().submit([weak_this = make_weak_ptr(), path = m_requested_url.file_path(), access = m_local_file_access, event_loop = Core::EventLoop::current_weak()] mutable {
auto read_local_file = [&] -> ErrorOr<LocalFile> {
- auto file = TRY(Core::File::adopt_fd(TRY(open_local_file_for_renderer(path)).take_fd(), Core::File::OpenMode::Read));
+ auto opened = TRY(access.has<UserSelectedLocalFile>()
+ ? open_local_file_the_user_chose(path)
+ : open_local_file_for_renderer(path, access.get<Vector<LocalFileRoot>>()));
+ auto file = TRY(Core::File::adopt_fd(opened.file.fd(), Core::File::OpenMode::Read));
+ (void)opened.file.take_fd();
if (TRY(Core::Directory::is_valid_directory(file->fd())))
return Error::from_errno(EISDIR);
auto stat = TRY(file->stat());
- return LocalFile { TRY(file->read_until_eof()), stat.st_mtime };
+ return LocalFile { TRY(file->read_until_eof()), stat.st_mtime, move(opened.canonical_path) };
};
auto local_file = read_local_file();
@@ -469,11 +473,24 @@ void NavigationLoader::read_local_file_for_response()
});
}
+Optional<LocalFileRoot> NavigationLoader::root_of_local_file(ByteString const& canonical_path) const
+{
+ if (m_local_file_access.has<UserSelectedLocalFile>())
+ return Application::local_file_grant_policy().root_for_opened_file(canonical_path);
+ return m_local_file_access.get<Vector<LocalFileRoot>>().first_matching([&](auto const& root) { return root.covers(canonical_path); }).copy();
+}
+
void NavigationLoader::did_read_local_file_for_response(ErrorOr<LocalFile> local_file)
{
if (!m_completion_steps)
return;
+ if (!local_file.is_error()) {
+ m_local_file_root = root_of_local_file(local_file.value().canonical_path);
+ if (!m_local_file_root.has_value())
+ local_file = Error::from_errno(EACCES);
+ }
+
// NB: A file the UI process cannot read creates an error document, as a network error does.
if (local_file.is_error()) {
m_result->navigation_params = Web::HTML::NavigationParamsNullOrError { Utf16String::formatted("{}", local_file.error()) };
diff --git a/Libraries/LibWebView/NavigationLoader.h b/Libraries/LibWebView/NavigationLoader.h
index 250dc0eee93..0e691b26d1e 100644
--- a/Libraries/LibWebView/NavigationLoader.h
+++ b/Libraries/LibWebView/NavigationLoader.h
@@ -24,6 +24,7 @@
#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
#include <LibWebView/Export.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
#include <LibWebView/RequestServerManager.h>
#include <time.h>
@@ -37,16 +38,9 @@ class WEBVIEW_API NavigationLoader final
public:
AK_ALLOC_WITH_KMALLOC;
- // Whether the UI process may read the local file that the request's file: URL names, for the process creating the
- // document: the UI process admitted a navigation to the URL, or its entry's document state held local file content.
- enum class MayReadLocalFile : bool {
- No,
- Yes,
- };
-
- static NonnullRefPtr<NavigationLoader> create(Web::HTML::NavigationPopulationRequest request, MayReadLocalFile may_read_local_file = MayReadLocalFile::No)
+ static NonnullRefPtr<NavigationLoader> create(Web::HTML::NavigationPopulationRequest request, LocalFileAccess local_file_access = {})
{
- return adopt_ref(*new NavigationLoader(move(request), may_read_local_file));
+ return adopt_ref(*new NavigationLoader(move(request), move(local_file_access)));
}
~NavigationLoader();
@@ -88,6 +82,7 @@ public:
// The host's client that RequestServer was told may adopt the response body.
Optional<int> response_body_adopter_client_id() const { return m_response_body_adopter_client_id; }
Web::HTML::NavigationPopulationRequest const& request() const { return m_request; }
+ Optional<LocalFileRoot> const& local_file_root() const { return m_local_file_root; }
Web::HTML::NavigationPopulationResult const& result() const;
Web::HTML::NavigationPopulationResult take_result();
void reclaim_response_body_after_failed_handoff();
@@ -117,18 +112,20 @@ public:
static void discard(WebContentClient const& population_worker, Web::HTML::NavigationPopulationResult&);
private:
- NavigationLoader(Web::HTML::NavigationPopulationRequest request, MayReadLocalFile may_read_local_file)
+ NavigationLoader(Web::HTML::NavigationPopulationRequest request, LocalFileAccess local_file_access)
: m_request(move(request))
, m_requested_url(m_request.history_entry.url)
- , m_may_read_local_file(may_read_local_file)
+ , m_local_file_access(move(local_file_access))
{
}
struct LocalFile {
ByteBuffer contents;
time_t modified_time { 0 };
+ ByteString canonical_path;
};
void read_local_file_for_response();
+ Optional<LocalFileRoot> root_of_local_file(ByteString const& canonical_path) const;
void did_read_local_file_for_response(ErrorOr<LocalFile>);
void determine_the_origin_of_the_response();
@@ -142,7 +139,8 @@ private:
Web::HTML::NavigationPopulationRequest m_request;
// The URL the request was made for, before the process that fetched the response reported where it ended up.
URL::URL m_requested_url;
- MayReadLocalFile m_may_read_local_file { MayReadLocalFile::No };
+ LocalFileAccess m_local_file_access;
+ Optional<LocalFileRoot> m_local_file_root;
Optional<Web::HTML::NavigationPopulationResult> m_result;
RefPtr<Requests::Request> m_response_body_request;
RefPtr<HTTP::HeaderList> m_response_header_list;
diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.h
index 84b0d9642f3..ad3a7e51e4b 100644
--- a/Libraries/LibWebView/Options.h
+++ b/Libraries/LibWebView/Options.h
@@ -113,6 +113,8 @@ struct BrowserOptions {
DisableSandbox disable_sandbox { DisableSandbox::No };
ForceVideoDecoderServer force_video_decoder_server { ForceVideoDecoderServer::No };
Vector<ByteString> content_blocker_list_paths {};
+ // In test mode, opening a file under this directory grants access to the whole directory.
+ Optional<ByteString> local_file_root_for_tests {};
// How much memory a WebContent process may use before it is ended. Zero means that there is no limit, and no value
// means the default limit for this machine.
Optional<u64> web_content_memory_limit_in_bytes {};
diff --git a/Libraries/LibWebView/SessionHistory.cpp b/Libraries/LibWebView/SessionHistory.cpp
index 10e8aad95b2..e4812907ad1 100644
--- a/Libraries/LibWebView/SessionHistory.cpp
+++ b/Libraries/LibWebView/SessionHistory.cpp
@@ -258,7 +258,7 @@ static void for_each_document_state(Vector<NonnullRefPtr<CanonicalSessionHistory
}
}
-ErrorOr<void> TraversableSessionHistory::restore_from_ui_snapshot(Vector<Web::HTML::SessionHistoryEntryDescriptor> entries, Vector<i32> used_steps, size_t current_used_step_index, Function<Web::HTML::CrossProcessId()> allocate_cross_process_id, Vector<Web::HTML::CrossProcessId> const& document_states_holding_local_file_content)
+ErrorOr<void> TraversableSessionHistory::restore_from_ui_snapshot(Vector<Web::HTML::SessionHistoryEntryDescriptor> entries, Vector<i32> used_steps, size_t current_used_step_index, Function<Web::HTML::CrossProcessId()> allocate_cross_process_id, Vector<DocumentStateLocalFileRoot> const& local_file_roots_of_document_states)
{
TRY(validate_snapshot_is_restorable(entries, used_steps, current_used_step_index));
@@ -267,15 +267,15 @@ ErrorOr<void> TraversableSessionHistory::restore_from_ui_snapshot(Vector<Web::HT
m_entries = TRY(entries_from_descriptors(entries));
m_current_session_history_step = used_steps[current_used_step_index];
- HashTable<Web::HTML::CrossProcessId> restored_ids_holding_local_file_content;
- for (auto id : document_states_holding_local_file_content) {
+ HashMap<Web::HTML::CrossProcessId, LocalFileRoot> restored_local_file_roots;
+ for (auto const& [id, root] : local_file_roots_of_document_states) {
if (auto restored_id = assigned_ids.get(id); restored_id.has_value())
- restored_ids_holding_local_file_content.set(*restored_id);
+ restored_local_file_roots.set(*restored_id, root);
}
- if (!restored_ids_holding_local_file_content.is_empty()) {
+ if (!restored_local_file_roots.is_empty()) {
for_each_document_state(m_entries, [&](CanonicalDocumentState& document_state) {
- if (restored_ids_holding_local_file_content.contains(document_state.id))
- document_state.held_local_file_content = true;
+ if (auto root = restored_local_file_roots.get(document_state.id); root.has_value())
+ document_state.local_file_root = *root;
});
}
return {};
@@ -415,15 +415,15 @@ size_t TraversableSessionHistory::current_used_step_index() const
return used_steps().find_first_index(get_the_used_step(m_current_session_history_step).value()).value();
}
-Vector<Web::HTML::CrossProcessId> TraversableSessionHistory::document_states_holding_local_file_content() const
+Vector<DocumentStateLocalFileRoot> TraversableSessionHistory::local_file_roots_of_document_states() const
{
- Vector<Web::HTML::CrossProcessId> ids;
+ Vector<DocumentStateLocalFileRoot> roots;
HashTable<Web::HTML::CrossProcessId> seen_ids;
for_each_document_state(m_entries, [&](CanonicalDocumentState& document_state) {
- if (document_state.held_local_file_content && seen_ids.set(document_state.id) == HashSetResult::InsertedNewEntry)
- ids.append(document_state.id);
+ if (document_state.local_file_root.has_value() && seen_ids.set(document_state.id) == HashSetResult::InsertedNewEntry)
+ roots.append({ document_state.id, *document_state.local_file_root });
});
- return ids;
+ return roots;
}
Vector<Web::HTML::SessionHistoryEntryDescriptor> TraversableSessionHistory::entries() const
diff --git a/Libraries/LibWebView/SessionHistory.h b/Libraries/LibWebView/SessionHistory.h
index 42767ade660..ff05b8d2789 100644
--- a/Libraries/LibWebView/SessionHistory.h
+++ b/Libraries/LibWebView/SessionHistory.h
@@ -20,6 +20,13 @@
namespace WebView {
+struct DocumentStateLocalFileRoot {
+ Web::HTML::CrossProcessId document_state_id;
+ LocalFileRoot root;
+
+ bool operator==(DocumentStateLocalFileRoot const&) const = default;
+};
+
inline constexpr size_t MAX_NESTED_HISTORY_DEPTH = 16;
// NB: The UI process holds the traversable's session history, so that it survives WebContent process swaps and crash
@@ -46,7 +53,7 @@ public:
size_t current_top_level_entry_index() const;
bool initialize_for_testing(Vector<Web::HTML::SessionHistoryEntryDescriptor>, Vector<i32> used_steps, size_t current_used_step_index);
- [[nodiscard]] ErrorOr<void> restore_from_ui_snapshot(Vector<Web::HTML::SessionHistoryEntryDescriptor> entries, Vector<i32> used_steps, size_t current_used_step_index, Function<Web::HTML::CrossProcessId()> allocate_cross_process_id, Vector<Web::HTML::CrossProcessId> const& document_states_holding_local_file_content = {});
+ [[nodiscard]] ErrorOr<void> restore_from_ui_snapshot(Vector<Web::HTML::SessionHistoryEntryDescriptor> entries, Vector<i32> used_steps, size_t current_used_step_index, Function<Web::HTML::CrossProcessId()> allocate_cross_process_id, Vector<DocumentStateLocalFileRoot> const& local_file_roots_of_document_states = {});
Optional<i32> append_nested_history(CanonicalNavigable const& parent_navigable, CanonicalDocumentState& parent_document_state, Web::HTML::CrossProcessId child_navigable_id, NonnullRefPtr<CanonicalSessionHistoryEntry> history_entry);
bool remove_nested_history(CanonicalNavigable const& parent_navigable, Web::HTML::CrossProcessId parent_document_state_id, Web::HTML::CrossProcessId child_navigable_id);
void clear_the_forward_session_history();
@@ -58,7 +65,7 @@ public:
bool replace_session_history_entry(CanonicalNavigable const&, CanonicalSessionHistoryEntry const& entry_to_replace, NonnullRefPtr<CanonicalSessionHistoryEntry>);
void update_directive_state_value(Web::HTML::CrossProcessId, Optional<String>);
Vector<Web::HTML::SessionHistoryEntryDescriptor> entries() const;
- Vector<Web::HTML::CrossProcessId> document_states_holding_local_file_content() const;
+ Vector<DocumentStateLocalFileRoot> local_file_roots_of_document_states() const;
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
Vector<i32> used_steps() const;
@@ -95,10 +102,9 @@ struct SessionHistorySnapshot {
Vector<Web::HTML::SessionHistoryEntryDescriptor> entries;
Vector<i32> used_steps;
size_t current_used_step_index { 0 };
- // NB: The browser populated local file content for these document states, so it reads the file an entry of one
- // names when a history step populates it again. Only the browser holds this: a renderer reports entries, but
- // not this.
- Vector<Web::HTML::CrossProcessId> document_states_holding_local_file_content;
+ // NB: The roots saved for document states that held local file content, used when a history step populates them
+ // again. A renderer reports entries, but cannot supply these roots.
+ Vector<DocumentStateLocalFileRoot> local_file_roots_of_document_states;
};
WEBVIEW_API ErrorOr<void> validate_snapshot_is_restorable(Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, Vector<i32> const& used_steps, size_t current_used_step_index);
diff --git a/Libraries/LibWebView/Utilities.cpp b/Libraries/LibWebView/Utilities.cpp
index 900027ff165..8c30491161c 100644
--- a/Libraries/LibWebView/Utilities.cpp
+++ b/Libraries/LibWebView/Utilities.cpp
@@ -5,6 +5,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
#include <AK/LexicalPath.h>
@@ -42,17 +43,21 @@ ErrorOr<Web::HTML::SelectedFile> create_selected_file(ByteString const& file_pat
return Web::HTML::SelectedFile { move(name), IPC::File::adopt_file(move(file)) };
}
-ErrorOr<IPC::File> open_local_file_for_renderer(ByteString const& path)
+static ErrorOr<OpenedLocalFile> open_local_file(ByteString const& path, Optional<ReadonlySpan<LocalFileRoot>> roots)
{
#if defined(AK_OS_WINDOWS)
+ // FIXME: Check the roots here too, once FileSystem::real_path() resolves links and drive-letter paths.
+ (void)roots;
auto file = TRY(Core::File::open(path, Core::File::OpenMode::Read));
// Files and directories are disk handles, while devices and pipes are not.
if (GetFileType(to_handle(file->fd())) != FILE_TYPE_DISK)
return Error::from_errno(EACCES);
- return IPC::File::adopt_file(move(file));
+ return OpenedLocalFile { IPC::File::adopt_file(move(file)), LexicalPath::canonicalized_path(path) };
#else
auto canonical_path = TRY(FileSystem::real_path(path));
+ if (roots.has_value() && !any_of(*roots, [&](auto const& root) { return root.covers(canonical_path); }))
+ return Error::from_errno(EACCES);
# if defined(AK_OS_MACOS)
// A /dev/fd entry opens a descriptor of the UI process, which reads as whatever file is behind it. Only the path
@@ -71,10 +76,23 @@ ErrorOr<IPC::File> open_local_file_for_renderer(ByteString const& path)
return Error::from_errno(EACCES);
# endif
- return IPC::File::adopt_file(move(file));
+ return OpenedLocalFile { IPC::File::adopt_file(move(file)), move(canonical_path) };
#endif
}
+ErrorOr<OpenedLocalFile> open_local_file_for_renderer(ByteString const& path, ReadonlySpan<LocalFileRoot> roots)
+{
+ // NB: Windows doesn't check the roots yet, so a renderer without any is refused before it gets there.
+ if (roots.is_empty())
+ return Error::from_errno(EACCES);
+ return open_local_file(path, roots);
+}
+
+ErrorOr<OpenedLocalFile> open_local_file_the_user_chose(ByteString const& path)
+{
+ return open_local_file(path, {});
+}
+
ErrorOr<JsonObject> read_json_file(ByteString const& path)
{
auto file = Core::File::open(path, Core::File::OpenMode::Read);
diff --git a/Libraries/LibWebView/Utilities.h b/Libraries/LibWebView/Utilities.h
index 251d20991c4..58291065251 100644
--- a/Libraries/LibWebView/Utilities.h
+++ b/Libraries/LibWebView/Utilities.h
@@ -16,15 +16,24 @@
#include <LibWebCommon/Forward.h>
#include <LibWebCommon/WebView/Utilities.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
namespace WebView {
WEBVIEW_API ErrorOr<Web::HTML::SelectedFile> create_selected_file(ByteString const&);
-// Opens a local file a renderer asked for, read-only, once its symbolic links are resolved. Anything but a regular file
-// or a directory is refused, as Core::File::open_regular_file_or_directory() refuses it, and so is a file on devfs on
-// macOS, or a process information or sysfs file on Linux.
-WEBVIEW_API ErrorOr<IPC::File> open_local_file_for_renderer(ByteString const& path);
+struct OpenedLocalFile {
+ IPC::File file;
+ ByteString canonical_path;
+};
+
+// Opens a local file a renderer asked for, read-only, if one of the roots covers it once its symbolic links are
+// resolved. Anything but a regular file or a directory is refused, as Core::File::open_regular_file_or_directory()
+// refuses it, and so is a file on devfs on macOS, or a process information or sysfs file on Linux.
+WEBVIEW_API ErrorOr<OpenedLocalFile> open_local_file_for_renderer(ByteString const& path, ReadonlySpan<LocalFileRoot>);
+
+// Opens a local file the user chose, wherever it is, as open_local_file_for_renderer() opens one under its roots.
+WEBVIEW_API ErrorOr<OpenedLocalFile> open_local_file_the_user_chose(ByteString const& path);
WEBVIEW_API ErrorOr<JsonObject> read_json_file(ByteString const& path);
WEBVIEW_API ErrorOr<void> write_json_file(ByteString const& path, JsonValue const& value);
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index e8d169b0f15..6882431ab30 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -888,24 +888,26 @@ void ViewImplementation::set_has_system_focus(bool has_system_focus)
void ViewImplementation::load_from_browser_ui(URL::URL const& url, Web::Bindings::NavigationHistoryBehavior history_handling)
{
- load(traversable().prepare_navigation(url, {}, history_handling));
+ load(traversable().prepare_navigation(url, {}, history_handling), UserSelectedLocalFile {});
}
// A navigation a page asked the browser's UI to start for it — a link opened with a middle-click, e.g. — whose
// source is still that page.
-void ViewImplementation::load(Web::HTML::PreparedNavigationDescriptor navigation)
+void ViewImplementation::load(Web::HTML::PreparedNavigationDescriptor navigation, LocalFileAccess local_file_access)
{
if (on_before_browser_initiated_navigation)
on_before_browser_initiated_navigation();
- prepare_for_navigation_after_crash(NavigationToRetry { navigation.url, prepare_navigation_to_retry(navigation) });
+ if (auto const& fetch_client = navigation.source_snapshot_params.fetch_client; local_file_access.has<Empty>() && fetch_client.has_value())
+ local_file_access = WebContentClient::local_file_access_of_process_hosting(fetch_client->id);
+ prepare_for_navigation_after_crash(NavigationToRetry { navigation.url, prepare_navigation_to_retry(navigation), local_file_access });
m_last_stopped_navigation.clear();
if (navigation.url.scheme() != "javascript"sv) {
if (navigation.url.fragment().has_value() && navigation.url.fragment()->contains(":~:"sv))
m_text_fragment_indication_is_visible = true;
m_browser_ui_load = BrowserUILoad { navigation.navigation_id, navigation.url };
}
- traversable().begin_navigation(move(navigation));
+ traversable().begin_navigation(move(navigation), {}, move(local_file_access));
if (traversable().has_uncommitted_navigation())
set_loading_state(true);
dump_session_history("load"sv);
@@ -4369,8 +4371,8 @@ Optional<ViewImplementation&> ViewImplementation::find_view_by_handle(StringView
void ViewImplementation::load_for_webdriver_navigation(URL::URL const& url)
{
auto navigation = traversable().prepare_navigation(url);
- prepare_for_navigation_after_crash(NavigationToRetry { url, prepare_navigation_to_retry(navigation) });
- traversable().begin_navigation(move(navigation));
+ prepare_for_navigation_after_crash(NavigationToRetry { url, prepare_navigation_to_retry(navigation), UserSelectedLocalFile {} });
+ traversable().begin_navigation(move(navigation), {}, UserSelectedLocalFile {});
}
void ViewImplementation::did_start_webdriver_navigation()
@@ -4534,7 +4536,7 @@ SessionHistorySnapshot ViewImplementation::session_history_snapshot() const
.entries = session_history.entries(),
.used_steps = session_history.used_steps(),
.current_used_step_index = session_history.current_used_step_index(),
- .document_states_holding_local_file_content = session_history.document_states_holding_local_file_content(),
+ .local_file_roots_of_document_states = session_history.local_file_roots_of_document_states(),
};
}
@@ -4878,18 +4880,18 @@ Optional<ViewImplementation::NavigationToRetry> ViewImplementation::navigation_t
navigation = traversable().navigation_being_finalized();
if (!navigation)
return {};
- return NavigationToRetry { navigation->url, navigation->retry };
+ return NavigationToRetry { navigation->url, navigation->retry, navigation->local_file_access };
}
void ViewImplementation::retry_navigation(NavigationToRetry retry, Web::Bindings::NavigationHistoryBehavior history_handling)
{
if (!retry.navigation.has_value()) {
- load_from_browser_ui(retry.url, history_handling);
+ load(traversable().prepare_navigation(retry.url, {}, history_handling), move(retry.local_file_access));
return;
}
auto navigation = retry.navigation.release_value();
navigation.history_handling = history_handling;
- load(move(navigation));
+ load(move(navigation), move(retry.local_file_access));
}
void ViewImplementation::prepare_for_navigation_after_crash(Optional<NavigationToRetry> navigation_to_retry)
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 7ee496a125e..ef58676a231 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -275,10 +275,11 @@ public:
void synchronized_resize_committed(Badge<CompositorPresentationClient>, u64 token) { did_commit_synchronized_resize(token); }
void set_has_system_focus(bool);
+ // A URL the user chose in the browser's UI. Loading a file: URL this way grants a root for that file.
void load_from_browser_ui(URL::URL const&, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);
void open_url_in_new_tab(URL::URL const&, Web::HTML::ActivateTab);
void open_url_in_new_window(URL::URL const&, IsPrivate);
- void load(Web::HTML::PreparedNavigationDescriptor);
+ void load(Web::HTML::PreparedNavigationDescriptor, LocalFileAccess = {});
void open_navigation_in_new_tab(Web::HTML::PreparedNavigationDescriptor, Web::HTML::ActivateTab);
void open_navigation_in_new_window(Web::HTML::PreparedNavigationDescriptor, IsPrivate);
void set_next_history_visit_transition(HistoryVisitTransition transition) { m_history_visit_transition_for_next_load = transition; }
@@ -930,6 +931,7 @@ protected:
struct NavigationToRetry {
URL::URL url;
Optional<Web::HTML::PreparedNavigationDescriptor> navigation;
+ LocalFileAccess local_file_access {};
};
Optional<NavigationToRetry> navigation_to_retry_for_ongoing_navigation() const;
void retry_navigation(NavigationToRetry, Web::Bindings::NavigationHistoryBehavior);
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 5025dc0247b..8bab6aa85a0 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -813,7 +813,38 @@ bool WebContentClient::renderers_may_synthesize_input_for_testing()
bool WebContentClient::may_read_local_files() const
{
- return m_has_hosted_local_file_content;
+ return !m_local_file_roots.is_empty();
+}
+
+ErrorOr<void> WebContentClient::add_local_file_root(LocalFileRoot root)
+{
+ if (m_local_file_roots.contains_slow(root))
+ return {};
+ // NB: Site isolation places local file content only in a process of its root, so a second root here would merge
+ // what two folders' pages may read. It's refused rather than added.
+ if (!m_local_file_roots.is_empty() && Application::the().tab_processes() != TabProcesses::PerTabWithoutSiteIsolation)
+ return Error::from_string_literal("A process may read local files under one root only");
+ m_local_file_roots.append(move(root));
+ return {};
+}
+
+LocalFileAccess WebContentClient::local_file_access() const
+{
+ if (m_local_file_roots.is_empty())
+ return {};
+ return m_local_file_roots;
+}
+
+LocalFileAccess WebContentClient::local_file_access_of_process_hosting(Web::HTML::EnvironmentId const& environment_id)
+{
+ LocalFileAccess local_file_access;
+ for_each_client([&](WebContentClient& client) {
+ if (!client.hosted_environment(environment_id).has_value())
+ return IterationDecision::Continue;
+ local_file_access = client.local_file_access();
+ return IterationDecision::Break;
+ });
+ return local_file_access;
}
Messages::WebContentClient::DidRequestAllCookiesWebdriverResponse WebContentClient::did_request_all_cookies_webdriver(URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context)
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 48a1ae4d202..4b0502303bc 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -63,6 +63,7 @@
#include <LibWebView/BrowsingSession.h>
#include <LibWebView/ChildIdentity.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
#include <LibWebView/RequestServerSiteBindings.h>
#include <LibWebView/StorageAreaRegistry.h>
#include <LibWebView/WebContentPage.h>
@@ -141,10 +142,13 @@ public:
// Connects a client to the ImageDecoder of this process, for its main thread or for a worker on a thread of it.
Optional<IPC::TransportHandle> connect_new_image_decoder_client(Optional<u64>& client_generation);
- // A process that has hosted local file content may read local files. Site isolation gives such content processes
- // of its own, which host nothing else.
- bool has_hosted_local_file_content() const { return m_has_hosted_local_file_content; }
- void set_has_hosted_local_file_content() { m_has_hosted_local_file_content = true; }
+ // The roots of the local file content the process has hosted, under which it may read local files. Site isolation
+ // gives such content processes of their own, one per root, which host nothing else.
+ Vector<LocalFileRoot> const& local_file_roots() const { return m_local_file_roots; }
+ ErrorOr<void> add_local_file_root(LocalFileRoot);
+ // A page's navigation reads a local file only under the roots of the process it came from, and grants none.
+ LocalFileAccess local_file_access() const;
+ static LocalFileAccess local_file_access_of_process_hosting(Web::HTML::EnvironmentId const&);
// The WebUI whose documents the process has hosted, whose channel the process may have. Site isolation gives such
// documents processes of their own, which host nothing else.
Optional<String> const& hosted_web_ui() const { return m_hosted_web_ui; }
@@ -281,7 +285,7 @@ private:
Optional<Utf16String> m_site_of_hosted_documents;
Optional<u64> m_image_decoder_client_generation;
bool m_has_hosted_documents_of_several_sites { false };
- bool m_has_hosted_local_file_content { false };
+ Vector<LocalFileRoot> m_local_file_roots;
Optional<String> m_hosted_web_ui;
Optional<URL::Origin> m_origin_of_hosted_tabs;
bool m_hosted_tabs_are_origin_keyed { false };
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index c28d514ca08..1951a702ad1 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -773,7 +773,7 @@ void WebContentPage::did_request_navigation_of_navigable(Web::HTML::CrossProcess
// 3. Set initiatorOriginSnapshot to sourceDocument's origin.
navigation.initiator_origin_snapshot = source_document.origin();
- target->begin_navigation(move(navigation), move(source_page));
+ target->begin_navigation(move(navigation), move(source_page), client().local_file_access());
}
static bool navigation_can_violate(Web::ContentSecurityPolicy::RemoteViolationDirective directive, CanonicalNavigable const& navigable, Web::HTML::NavigationPopulationRequest const& request)
@@ -1688,18 +1688,13 @@ void WebContentPage::did_change_picture_in_picture_player_controls_visibility(bo
void WebContentPage::did_request_file(ByteString path, i32 request_id)
{
// NB: The renderer's sandbox keeps it out of the local file system, so this is the only way it can read a file.
- // Answer only a process that has hosted local file content: any other could read every file the user can. The
- // UI process reads the file a navigation names itself, for the process creating the document.
- if (!client().may_read_local_files()) {
- async_handle_file_return(EACCES, {}, request_id);
- return;
- }
-
- auto file = open_local_file_for_renderer(path);
+ // Answer only a process that has hosted local file content, for a file under its roots. The UI process reads
+ // the file a navigation names itself, for the process creating the document.
+ auto file = open_local_file_for_renderer(path, client().local_file_roots());
if (file.is_error())
async_handle_file_return(file.error().code(), {}, request_id);
else
- async_handle_file_return(0, file.release_value(), request_id);
+ async_handle_file_return(0, move(file.value().file), request_id);
}
// NB: For a file input, Element Send Keys selects the files listed in its text. The page running the command may read
@@ -1712,11 +1707,11 @@ void WebContentPage::did_request_file_for_webdriver(u64 command_id, ByteString p
return;
}
- auto file = open_local_file_for_renderer(path);
+ auto file = open_local_file_the_user_chose(path);
if (file.is_error())
async_handle_file_return(file.error().code(), {}, request_id);
else
- async_handle_file_return(0, file.release_value(), request_id);
+ async_handle_file_return(0, move(file.value().file), request_id);
}
void WebContentPage::did_request_color_picker(Color current_color)
@@ -2721,6 +2716,7 @@ void WebContentPage::did_request_navigation_start(Web::HTML::CrossProcessId navi
.sequence_number = target_navigable->top_level_traversable().next_sequence_number(),
.state = CanonicalNavigation::CheckingIfUnloadingIsCanceled { start_request.release_value() },
.page = this,
+ .local_file_access = client().local_file_access(),
});
begin_navigation_unload_check(*target_navigable, navigation_id);
}
@@ -2764,8 +2760,9 @@ void WebContentPage::did_complete_navigation_unload_check(Web::HTML::CrossProces
Application::the().allocate_ui_process_cross_process_id());
population_request.target_snapshot_params.sandboxing_flags |= navigable->snapshot_target_snapshot_params().sandboxing_flags;
ongoing_navigation->history_entry = MUST(CanonicalSessionHistoryEntry::create_from_descriptor(Web::HTML::create_session_history_entry_descriptor(population_request.history_entry, 0)));
- // NB: The UI process admitted the navigation, so it reads the local file a file: URL names.
- ongoing_navigation->state = CanonicalNavigation::CreatingNavigationParams { NavigationLoader::create(move(population_request), NavigationLoader::MayReadLocalFile::Yes) };
+ // NB: The UI process admitted the navigation, so it reads a file: URL's file itself, with the navigation's local
+ // file access.
+ ongoing_navigation->state = CanonicalNavigation::CreatingNavigationParams { NavigationLoader::create(move(population_request), ongoing_navigation->local_file_access) };
async_create_navigation_params(ongoing_navigation->loader()->request());
// Requesting navigation params starts the fetch, so a view's top-level population begins its recorded
@@ -3808,10 +3805,14 @@ Messages::WebContentClient::DidAddBlobUrlEntryResponse WebContentPage::did_add_b
entry.origin = environment->origin();
// 4. Set store[url] to entry.
- // NB: A document created from the URL in another process reads local files as local file content does, so the
- // store remembers whether local file content added the entry.
- auto added_by_local_file_content = client().may_read_local_files() ? AddedByLocalFileContent::Yes : AddedByLocalFileContent::No;
- return client().session().blob_url_store->add_entry(move(url), move(entry), WeakPtr<WebContentClient> { client() }, added_by_local_file_content);
+ // NB: A document created from the URL in another process reads local files under the root of the content that
+ // added the entry, or of its process when that has just one.
+ Optional<LocalFileRoot> root_of_adder;
+ if (auto document = document_with_hosted_environment(environment_id); document.has_value() && document->local_file_root().has_value())
+ root_of_adder = document->local_file_root();
+ else if (client().local_file_roots().size() == 1)
+ root_of_adder = client().local_file_roots().first();
+ return client().session().blob_url_store->add_entry(move(url), move(entry), WeakPtr<WebContentClient> { client() }, move(root_of_adder));
}
// https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
diff --git a/Libraries/LibWebView/WebDriverBiDi.cpp b/Libraries/LibWebView/WebDriverBiDi.cpp
index 06049e30ed4..ca020c6aab4 100644
--- a/Libraries/LibWebView/WebDriverBiDi.cpp
+++ b/Libraries/LibWebView/WebDriverBiDi.cpp
@@ -1426,7 +1426,7 @@ static ErrorOr<Optional<StringView>, Web::WebDriver::Error> get_wait_condition(J
}
// https://w3c.github.io/webdriver-bidi/#await-a-navigation
-void WebDriverBiDi::await_a_navigation(CanonicalNavigable& navigable, URL::URL url, WaitCondition wait_condition, CommandResult on_complete)
+void WebDriverBiDi::await_a_navigation(CanonicalNavigable& navigable, URL::URL url, WaitCondition wait_condition, LocalFileAccess local_file_access, CommandResult on_complete)
{
// 1. Let navigation id be the string representation of a UUID based on truly random, or pseudo-random numbers.
// 2. Navigate navigable with resource request, and using navigable's active document as the source Document, with
@@ -1471,11 +1471,11 @@ void WebDriverBiDi::await_a_navigation(CanonicalNavigable& navigable, URL::URL u
if (navigable.is_top_level_traversable()) {
if (auto view = static_cast<CanonicalTraversable&>(navigable).view(); view.has_value()) {
- view->load(move(navigation));
+ view->load(move(navigation), move(local_file_access));
return;
}
}
- navigable.begin_navigation(move(navigation));
+ navigable.begin_navigation(move(navigation), {}, move(local_file_access));
}
void WebDriverBiDi::await_navigation_completion(Web::HTML::CrossProcessId navigable_id, Utf16String const& navigation_id, WaitCondition wait_condition, CommandResult on_complete)
@@ -1549,7 +1549,7 @@ void WebDriverBiDi::browsing_context_navigate(JsonObject const& params, CommandR
// 11. Let request be a new request whose URL is url record.
// 12. Return the result of await a navigation with navigable, request and wait condition.
- await_a_navigation(*navigable, url_record.release_value(), wait_condition, move(on_complete));
+ await_a_navigation(*navigable, url_record.release_value(), wait_condition, UserSelectedLocalFile {}, move(on_complete));
}
// https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload
@@ -1586,7 +1586,10 @@ void WebDriverBiDi::browsing_context_reload(JsonObject const& params, CommandRes
// id is passed through the history job to the replacement document.
// NB: A child navigable is navigated to the URL of its active document, which replaces its session history entry.
if (!navigable->is_top_level_traversable()) {
- await_a_navigation(*navigable, navigable->active_document_url(), wait_condition, move(on_complete));
+ LocalFileAccess local_file_access;
+ if (auto const& root = navigable->active_document().local_file_root(); root.has_value())
+ local_file_access = Vector { *root };
+ await_a_navigation(*navigable, navigable->active_document_url(), wait_condition, move(local_file_access), move(on_complete));
return;
}
diff --git a/Libraries/LibWebView/WebDriverBiDi.h b/Libraries/LibWebView/WebDriverBiDi.h
index da1dbc39275..46c2ba506ad 100644
--- a/Libraries/LibWebView/WebDriverBiDi.h
+++ b/Libraries/LibWebView/WebDriverBiDi.h
@@ -23,6 +23,7 @@
#include <LibWebCommon/WebDriver/BiDi.h>
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebView/Forward.h>
+#include <LibWebView/LocalFileRoot.h>
namespace WebView {
@@ -139,7 +140,7 @@ private:
Interactive,
Complete,
};
- void await_a_navigation(CanonicalNavigable&, URL::URL, WaitCondition, CommandResult);
+ void await_a_navigation(CanonicalNavigable&, URL::URL, WaitCondition, LocalFileAccess, CommandResult);
void await_navigation_completion(Web::HTML::CrossProcessId navigable_id, Utf16String const& navigation_id, WaitCondition, CommandResult);
void browsing_context_activate(JsonObject const& params, CommandResult);
diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cpp
index 828d837f705..e1487e3033d 100644
--- a/Libraries/LibWebView/WebWorkerClient.cpp
+++ b/Libraries/LibWebView/WebWorkerClient.cpp
@@ -100,11 +100,11 @@ void WebWorkerClient::remove_blob_url_entries()
session->blob_url_store->remove_entries_added_by(WeakPtr<WebWorkerClient> { *this });
}
-void WebWorkerClient::set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmentSettingsObject> inside_settings, bool may_read_local_files)
+void WebWorkerClient::set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmentSettingsObject> inside_settings, Vector<LocalFileRoot> local_file_roots)
{
m_top_level_origin = inside_settings->top_level_origin();
m_inside_settings = move(inside_settings);
- m_may_read_local_files = may_read_local_files;
+ m_local_file_roots = move(local_file_roots);
}
void WebWorkerClient::forget_inside_settings_of_closing_worker()
@@ -163,7 +163,11 @@ Messages::WebWorkerClient::DidAddBlobUrlEntryResponse WebWorkerClient::did_add_b
if (!session || !environment.has_value())
return 0;
entry.origin = environment->origin();
- return session->blob_url_store->add_entry(move(url), move(entry), WeakPtr<WebWorkerClient> { *this });
+
+ Optional<LocalFileRoot> root_of_adder;
+ if (m_local_file_roots.size() == 1)
+ root_of_adder = m_local_file_roots.first();
+ return session->blob_url_store->add_entry(move(url), move(entry), WeakPtr<WebWorkerClient> { *this }, move(root_of_adder));
}
void WebWorkerClient::did_remove_blob_url_entries(Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls)
@@ -188,17 +192,11 @@ void WebWorkerClient::did_request_file(ByteString path, i32 request_id)
if (!m_inside_settings)
return;
- // NB: As a page, a worker reads a local file only through this broker, and only local file content may.
- if (!m_may_read_local_files) {
- async_handle_file_return(EACCES, {}, request_id);
- return;
- }
-
- auto file = open_local_file_for_renderer(path);
+ auto file = open_local_file_for_renderer(path, m_local_file_roots);
if (file.is_error())
async_handle_file_return(file.error().code(), {}, request_id);
else
- async_handle_file_return(0, file.release_value(), request_id);
+ async_handle_file_return(0, move(file.value().file), request_id);
}
Messages::WebWorkerClient::DidIsKnownHstsHostResponse WebWorkerClient::did_is_known_hsts_host(String domain)
diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.h
index 07a86f79fb6..ab736f96d3e 100644
--- a/Libraries/LibWebView/WebWorkerClient.h
+++ b/Libraries/LibWebView/WebWorkerClient.h
@@ -54,11 +54,11 @@ public:
Optional<CanonicalEnvironmentSettingsObject const&> hosted_environment(Web::HTML::EnvironmentId const& environment_id) const;
- void set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmentSettingsObject>, bool may_read_local_files);
+ void set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmentSettingsObject>, Vector<LocalFileRoot> local_file_roots);
CanonicalWorkerEnvironmentSettingsObject const* inside_settings() const { return m_inside_settings.ptr(); }
void forget_inside_settings_of_closing_worker();
Optional<URL::Origin> const& top_level_origin() const { return m_top_level_origin; }
- bool may_read_local_files() const { return m_may_read_local_files; }
+ Vector<LocalFileRoot> const& local_file_roots() const { return m_local_file_roots; }
void keep_script_blob_url_until_script_loads(BlobURLHandle handle) { m_script_blob_url = move(handle); }
virtual void did_close_worker() override;
@@ -97,7 +97,7 @@ private:
OwnPtr<CanonicalWorkerEnvironmentSettingsObject> m_inside_settings;
Optional<URL::Origin> m_top_level_origin;
- bool m_may_read_local_files { false };
+ Vector<LocalFileRoot> m_local_file_roots;
// Keeps the blob URL entry of the worker's script alive until the script is loaded, so that the owner can
// revoke the URL right after constructing the worker.
BlobURLHandle m_script_blob_url;
diff --git a/Libraries/LibWebView/WorkerAgentManager.cpp b/Libraries/LibWebView/WorkerAgentManager.cpp
index 8786de6e009..aaff7f7ee6f 100644
--- a/Libraries/LibWebView/WorkerAgentManager.cpp
+++ b/Libraries/LibWebView/WorkerAgentManager.cpp
@@ -174,7 +174,7 @@ WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(We
m_shared_workers.set(agent.shared_worker_key, agent_id);
m_agents.set(agent_id, move(agent));
- start_worker(*client, move(request), *outside_settings, has_cross_site_ancestor, owner_client.may_read_local_files(), host_has_only_this_worker);
+ start_worker(*client, move(request), *outside_settings, has_cross_site_ancestor, owner_client.local_file_roots(), host_has_only_this_worker);
// NB: The task manager lists a process with the site of its pages. One that has none left only runs on for its shared
// workers, so it goes by the site of their origin.
@@ -194,7 +194,7 @@ void WorkerAgentManager::register_dedicated_worker(WebContentClient& owner_clien
.is_private = owner_client.is_private(),
.process = owner_client,
.request_server_site_bindings = owner_client.request_server_site_bindings(),
- .may_read_local_files = owner_client.may_read_local_files(),
+ .local_file_roots = owner_client.local_file_roots(),
.has_cross_site_ancestor = page_environment_has_cross_site_ancestor(owner_client, page_id, *outside_settings),
};
register_dedicated_worker(owner, *outside_settings, move(request), move(worker_transport));
@@ -209,7 +209,7 @@ void WorkerAgentManager::register_dedicated_worker(WebWorkerClient& owner_client
.is_private = owner_client.is_private(),
.process = *host,
.request_server_site_bindings = owner_client.request_server_site_bindings(),
- .may_read_local_files = owner_client.may_read_local_files(),
+ .local_file_roots = owner_client.local_file_roots(),
.has_cross_site_ancestor = static_cast<CanonicalWorkerEnvironmentSettingsObject const&>(*outside_settings).has_cross_site_ancestor(),
};
register_dedicated_worker(owner, *outside_settings, move(request), move(worker_transport));
@@ -238,7 +238,7 @@ void WorkerAgentManager::register_dedicated_worker(DedicatedWorkerOwner const& o
}
auto client = client_or_error.release_value();
- start_worker(*client, move(request), outside_settings, owner.has_cross_site_ancestor, owner.may_read_local_files, false);
+ start_worker(*client, move(request), outside_settings, owner.has_cross_site_ancestor, owner.local_file_roots, false);
}
bool WorkerAgentManager::page_environment_has_cross_site_ancestor(WebContentClient& client, Web::PageId page_id, CanonicalEnvironmentSettingsObject const& environment)
@@ -289,7 +289,7 @@ ErrorOr<NonnullRefPtr<WebWorkerClient>> WorkerAgentManager::create_worker_client
return client;
}
-void WorkerAgentManager::start_worker(WebWorkerClient& client, Web::HTML::WorkerAgentStartRequest request, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, bool owner_may_read_local_files, bool has_process_to_itself)
+void WorkerAgentManager::start_worker(WebWorkerClient& client, Web::HTML::WorkerAgentStartRequest request, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, Vector<LocalFileRoot> const& owner_local_file_roots, bool has_process_to_itself)
{
// https://html.spec.whatwg.org/multipage/workers.html#set-up-a-worker-environment-settings-object
// 3. Let origin be a unique opaque origin if worker global scope's url's scheme is "data"; otherwise outside
@@ -308,8 +308,7 @@ void WorkerAgentManager::start_worker(WebWorkerClient& client, Web::HTML::Worker
// NB: A worker reads local files as its owner does. A worker of a file origin that local file content starts is
// local file content too.
- auto may_read_local_files = inside_origin.is_file_origin() && owner_may_read_local_files;
- client.set_inside_settings(move(inside_settings), may_read_local_files);
+ client.set_inside_settings(move(inside_settings), inside_origin.is_file_origin() ? owner_local_file_roots : Vector<LocalFileRoot> {});
// NB: The worker's URL was parsed with its blob URL entry, so revoking the URL must not stop the worker from
// fetching its script.
diff --git a/Libraries/LibWebView/WorkerAgentManager.h b/Libraries/LibWebView/WorkerAgentManager.h
index 71482a4c971..de34ab122b6 100644
--- a/Libraries/LibWebView/WorkerAgentManager.h
+++ b/Libraries/LibWebView/WorkerAgentManager.h
@@ -110,7 +110,7 @@ private:
IsPrivate is_private { IsPrivate::No };
WebContentClient& process;
RequestServerSiteBindings const& request_server_site_bindings;
- bool may_read_local_files { false };
+ Vector<LocalFileRoot> local_file_roots;
bool has_cross_site_ancestor { false };
};
void register_dedicated_worker(DedicatedWorkerOwner const&, CanonicalEnvironmentSettingsObject const& outside_settings, Web::HTML::WorkerAgentStartRequest, IPC::TransportHandle worker_transport);
@@ -119,7 +119,7 @@ private:
static bool page_environment_has_cross_site_ancestor(WebContentClient&, Web::PageId, CanonicalEnvironmentSettingsObject const&);
bool has_reached_worker_limit(IsPrivate, CanonicalEnvironmentSettingsObject const& outside_settings) const;
ErrorOr<NonnullRefPtr<WebWorkerClient>> create_worker_client(NonnullOwnPtr<IPC::Transport>, Web::HTML::WorkerAgentId, WebContentClient& host, RequestServerSiteBindings const& owner_request_server_site_bindings);
- static void start_worker(WebWorkerClient&, Web::HTML::WorkerAgentStartRequest, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, bool owner_may_read_local_files, bool has_process_to_itself);
+ static void start_worker(WebWorkerClient&, Web::HTML::WorkerAgentStartRequest, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, Vector<LocalFileRoot> const& owner_local_file_roots, bool has_process_to_itself);
void notify_worker_script_load_failure(Owner const&);
void notify_worker_content_security_policy_violation(Owner const&, u64 policy_index, String const& effective_directive, URL::URL const& resource);
diff --git a/Services/Hub/HubClient.ipc b/Services/Hub/HubClient.ipc
index cbac8eef77a..0f9fcbd8b79 100644
--- a/Services/Hub/HubClient.ipc
+++ b/Services/Hub/HubClient.ipc
@@ -184,12 +184,24 @@ struct WebView::ContextMenuRequest {
Optional<Web::MediaContextMenu> media;
}
+[ExistingCpp]
+struct WebView::LocalFileRoot {
+ ByteString path;
+ WebView::LocalFileRoot::Scope scope;
+}
+
+[ExistingCpp]
+struct WebView::DocumentStateLocalFileRoot {
+ Web::HTML::CrossProcessId document_state_id;
+ WebView::LocalFileRoot root;
+}
+
[ExistingCpp]
struct WebView::SessionHistorySnapshot {
Vector<Web::HTML::SessionHistoryEntryDescriptor> entries;
Vector<i32> used_steps;
size_t current_used_step_index;
- Vector<Web::HTML::CrossProcessId> document_states_holding_local_file_content;
+ Vector<WebView::DocumentStateLocalFileRoot> local_file_roots_of_document_states;
}
// A language the tab's page can be translated into, perhaps after a download.
diff --git a/Tests/LibWeb/Text/expected/Fetch/file-url-subresources-of-system-files.txt b/Tests/LibWeb/Text/expected/Fetch/file-url-subresources-of-system-files.txt
new file mode 100644
index 00000000000..b0717ea5e47
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/file-url-subresources-of-system-files.txt
@@ -0,0 +1,9 @@
+a regular file: loaded
+/etc/hosts: refused
+/proc/self/maps: refused
+/proc/self/environ: refused
+/proc/self/fd/0: refused
+/sys/kernel/mm/transparent_hugepage/enabled: refused
+/dev/fd/0: refused
+/dev/stdin: refused
+/dev/null: refused
diff --git a/Tests/LibWeb/Text/input/Fetch/file-url-subresources-of-system-files.html b/Tests/LibWeb/Text/input/Fetch/file-url-subresources-of-system-files.html
new file mode 100644
index 00000000000..6a09289628a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/file-url-subresources-of-system-files.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A file: document loads other local files only under the root the browser granted it, which is the test tree here.
+ function load(url) {
+ return new Promise(resolve => {
+ const script = document.createElement("script");
+ script.src = url;
+ script.onload = () => resolve("loaded");
+ script.onerror = () => resolve("refused");
+ document.head.appendChild(script);
+ });
+ }
+
+ promiseTest(async () => {
+ println(`a regular file: ${await load(new URL("file-script-canary.js", window.location.href).href)}`);
+ for (const path of [
+ "/etc/hosts",
+ "/proc/self/maps",
+ "/proc/self/environ",
+ "/proc/self/fd/0",
+ "/sys/kernel/mm/transparent_hugepage/enabled",
+ "/dev/fd/0",
+ "/dev/stdin",
+ "/dev/null",
+ ])
+ println(`${path}: ${await load(`file://${path}`)}`);
+ });
+</script>
diff --git a/Tests/LibWeb/test-web/Application.cpp b/Tests/LibWeb/test-web/Application.cpp
index 680626a65ae..0853d4a7038 100644
--- a/Tests/LibWeb/test-web/Application.cpp
+++ b/Tests/LibWeb/test-web/Application.cpp
@@ -85,6 +85,11 @@ void Application::create_platform_arguments(Core::ArgsParser& args_parser)
void Application::create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions& request_server_options, WebView::WebContentOptions& web_content_options)
{
+ // NB: Tests load local files from all over the source tree, not just the directory of the test that loads them.
+ LexicalPath test_root { test_root_path };
+ auto is_in_source_tree = test_root.basename() == "LibWeb"sv && test_root.parent().basename() == "Tests"sv;
+ browser_options.local_file_root_for_tests = is_in_source_tree ? test_root.parent().parent().string() : test_root_path;
+
if (verify_style) {
// NB: The style engine checks what it installed against a cold computation of the document.
MUST(Core::Environment::set("LIBWEB_STYLE_SELFCHECK"sv, "1"sv, Core::Environment::Overwrite::Yes));
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 854a2f55274..aa49ad05af0 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -108,6 +108,7 @@ if (APPLE OR LINUX)
TestCrashReportReview.cpp
TestCrashReportStore.cpp
TestFontService.cpp
+ TestLocalFileRoot.cpp
TestOpenLocalFileForRenderer.cpp
TestRendererFontService.cpp
)
@@ -156,6 +157,7 @@ if (NOT WIN32)
TestInputMethodState.cpp
TestInspectDOMTree.cpp
TestLinkHoverStatus.cpp
+ TestLocalFileNavigation.cpp
TestNavigationDownloads.cpp
TestPictureInPictureUserActivation.cpp
TestPictureInPictureWindowControls.cpp
diff --git a/Tests/LibWebView/TestCompositorStartup.cpp b/Tests/LibWebView/TestCompositorStartup.cpp
index f8a14cb6bb7..ff9c5177534 100644
--- a/Tests/LibWebView/TestCompositorStartup.cpp
+++ b/Tests/LibWebView/TestCompositorStartup.cpp
@@ -9,7 +9,6 @@
#include <AK/LexicalPath.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
-#include <LibFileSystem/FileSystem.h>
#include <LibGfx/SystemTheme.h>
#include <LibTest/TestCase.h>
#include <LibURL/Parser.h>
@@ -68,8 +67,12 @@ TEST_CASE(a_video_that_starts_before_the_compositor_launches_plays_once_it_does)
Array arguments { "--temporary-profile"sv, "--enable-autoplay"sv };
auto app = TRY_OR_FAIL(environment.create_application<TestApplication>(arguments));
- // The tests run from this directory.
- auto video_path = TRY_OR_FAIL(FileSystem::real_path("../LibWeb/Assets/blue-with-second-in-gray-64x36.webm"sv));
+ // The tests run from this directory. A page reads only the files in its own folder, so the video is put beside it.
+ auto video = TRY_OR_FAIL(Core::File::open("../LibWeb/Assets/blue-with-second-in-gray-64x36.webm"sv, Core::File::OpenMode::Read));
+ auto video_path = LexicalPath::join(environment.directory(), "video.webm"sv).string();
+ auto video_copy = TRY_OR_FAIL(Core::File::open(video_path, Core::File::OpenMode::Write));
+ TRY_OR_FAIL(video_copy->write_until_depleted(TRY_OR_FAIL(video->read_until_eof())));
+ video_copy->close();
auto page_path = LexicalPath::join(environment.directory(), "video.html"sv).string();
auto page = TRY_OR_FAIL(Core::File::open(page_path, Core::File::OpenMode::Write));
TRY_OR_FAIL(page->write_formatted("<video autoplay muted src=\"{}\" oncanplay=\"document.title = 'canplay'\"></video>", URL::create_with_file_scheme(video_path)->serialize()));
diff --git a/Tests/LibWebView/TestImageDecoderIsolation.cpp b/Tests/LibWebView/TestImageDecoderIsolation.cpp
index ac8cfe66db2..7f7e9a624a1 100644
--- a/Tests/LibWebView/TestImageDecoderIsolation.cpp
+++ b/Tests/LibWebView/TestImageDecoderIsolation.cpp
@@ -9,6 +9,7 @@
#include <AK/HashTable.h>
#include <AK/LexicalPath.h>
#include <AK/Utf16String.h>
+#include <LibCore/Directory.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
#include <LibCore/System.h>
@@ -171,8 +172,12 @@ TEST_CASE(pdf_viewer_does_not_make_a_renderer_leave_the_image_decoder_of_its_sit
auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+ // The profile is beneath the environment's directory on Linux, so a page there would be granted only itself.
+ auto content_directory = LexicalPath::join(environment.directory(), "content"sv).string();
+ MUST(Core::Directory::create(content_directory, Core::Directory::CreateDirectories::Yes));
+
auto write_file = [&](StringView name, StringView contents) {
- auto path = LexicalPath::join(environment.directory(), name).string();
+ auto path = LexicalPath::join(content_directory, name).string();
auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));
MUST(file->write_until_depleted(contents.bytes()));
file->close();
diff --git a/Tests/LibWebView/TestLocalFileNavigation.cpp b/Tests/LibWebView/TestLocalFileNavigation.cpp
new file mode 100644
index 00000000000..3d29bd62535
--- /dev/null
+++ b/Tests/LibWebView/TestLocalFileNavigation.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "HeadlessTest.h"
+#include <AK/LexicalPath.h>
+#include <LibCore/Directory.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/File.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibGfx/SystemTheme.h>
+#include <LibTest/TestCase.h>
+#include <LibURL/URL.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/Utilities.h>
+#include <LibWebView/WebContentClient.h>
+
+namespace {
+
+class TestApplication : public Test::HeadlessApplication {
+ WEB_VIEW_APPLICATION(TestApplication)
+
+public:
+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)
+ : Test::HeadlessApplication(move(ladybird_binary_path))
+ {
+ }
+
+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override
+ {
+ browser_options.headless_mode = WebView::HeadlessMode::Test;
+ browser_options.allow_popups = WebView::AllowPopups::Yes;
+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;
+ }
+};
+
+}
+
+// A file the user opens grants its folder to the renderer that hosts it. A navigation the page starts reads a file only
+// under that folder, and grants nothing, while one the browser starts reads the file the user chose wherever it is.
+TEST_CASE(local_file_navigation)
+{
+ Test::HeadlessTestEnvironment environment { "TestLocalFileNavigation"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+
+ auto directory = TRY_OR_FAIL(FileSystem::real_path(environment.directory()));
+ auto inside = LexicalPath::join(directory, "inside"sv).string();
+ auto outside = LexicalPath::join(directory, "outside"sv).string();
+ TRY_OR_FAIL(Core::Directory::create(inside, Core::Directory::CreateDirectories::Yes));
+ TRY_OR_FAIL(Core::Directory::create(outside, Core::Directory::CreateDirectories::Yes));
+
+ auto write_page = [&](StringView directory, StringView title) {
+ auto path = LexicalPath::join(directory, ByteString::formatted("{}.html", title)).string();
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));
+ MUST(file->write_until_depleted(ByteString::formatted("<title>{}</title>", title)));
+ return URL::create_with_file_scheme(path).release_value();
+ };
+ auto start_page_url = write_page(inside, "start"sv);
+ auto next_page_url = write_page(inside, "next"sv);
+ auto outside_page_url = write_page(outside, "elsewhere"sv);
+
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ size_t loads_finished = 0;
+ view->on_load_finish = [&](auto const&) { ++loads_finished; };
+ Utf16String title;
+ view->on_title_change = [&](auto const& new_title) { title = new_title; };
+ // Wait out the initial about:blank load; navigating before it completes would drop the navigation.
+ Core::EventLoop::current().spin_until([&]() { return loads_finished >= 1; });
+
+ auto view_is_at = [&](URL::URL const& url) { return view->url().serialize() == url.serialize(); };
+ auto wait_for_load_of = [&](URL::URL const& url) {
+ auto expected_loads = loads_finished + 1;
+ Core::EventLoop::current().spin_until([&]() { return loads_finished >= expected_loads && view_is_at(url); });
+ };
+
+ view->load_from_browser_ui(start_page_url);
+ wait_for_load_of(start_page_url);
+ VERIFY(title == "start"sv);
+
+ // A navigation the page starts, to a file outside the folder the user opened, gets an error document.
+ view->run_javascript(MUST(String::formatted("location.href = '{}';", outside_page_url.serialize())));
+ wait_for_load_of(outside_page_url);
+ if (title == "elsewhere"sv)
+ FAIL("A page navigated to a file outside its root, and got its content");
+
+ // One to a file in that folder reads it.
+ view->load_from_browser_ui(start_page_url);
+ wait_for_load_of(start_page_url);
+ view->run_javascript("location.href = 'next.html';"_string);
+ wait_for_load_of(next_page_url);
+ VERIFY(title == "next"sv);
+
+ // The browser reads a file the user chose wherever it is.
+ view->load_from_browser_ui(outside_page_url);
+ wait_for_load_of(outside_page_url);
+ VERIFY(title == "elsewhere"sv);
+
+ // A page navigation from there still reads nothing in the first folder: the page's navigation grants nothing.
+ view->run_javascript(MUST(String::formatted("location.href = '{}';", start_page_url.serialize())));
+ wait_for_load_of(start_page_url);
+ if (title == "start"sv)
+ FAIL("A page navigated to a file outside its root, and got its content");
+}
+
+// A sandboxed srcdoc frame reads local files under the root of the file page that made it. The sandboxed documents of
+// the file origin share a process within a browsing context group, but not across roots, even for related tabs.
+TEST_CASE(sandboxed_frames_of_related_tabs_keep_their_roots_apart)
+{
+ Test::HeadlessTestEnvironment environment { "TestLocalFileNavigation"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+
+ auto directory = TRY_OR_FAIL(FileSystem::real_path(environment.directory()));
+ auto write_page = [&](StringView folder) {
+ auto folder_path = LexicalPath::join(directory, folder).string();
+ MUST(Core::Directory::create(folder_path, Core::Directory::CreateDirectories::Yes));
+ auto path = LexicalPath::join(folder_path, "frame.html"sv).string();
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));
+ MUST(file->write_until_depleted("<iframe sandbox srcdoc=\"sandboxed\"></iframe>"sv));
+ return URL::create_with_file_scheme(path).release_value();
+ };
+ auto first_page_url = write_page("first"sv);
+ auto second_page_url = write_page("second"sv);
+
+ auto sandboxed_frame_process = [](WebView::HeadlessWebView& view) -> WebView::WebContentClient* {
+ WebView::WebContentClient* process = nullptr;
+ view.traversable().for_each_in_subtree([&](WebView::CanonicalNavigable& navigable) {
+ if (auto host = navigable.active_document().host(); host && navigable.active_document().creation_url() == URL::about_srcdoc())
+ process = &host->client();
+ return IterationDecision::Break;
+ });
+ return process;
+ };
+
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ size_t loads_finished = 0;
+ view->on_load_finish = [&](auto const&) { ++loads_finished; };
+ Core::EventLoop::current().spin_until([&]() { return loads_finished >= 1; });
+
+ view->load_from_browser_ui(first_page_url);
+ Core::EventLoop::current().spin_until([&]() { return sandboxed_frame_process(*view) != nullptr; });
+ auto& first_process = *sandboxed_frame_process(*view);
+
+ OwnPtr<WebView::HeadlessWebView> popup;
+ view->on_new_web_view = [&](auto, auto, WebView::CanonicalTraversable& traversable) {
+ popup = WebView::HeadlessWebView::create_child(*view, traversable);
+ return popup->handle();
+ };
+ view->run_javascript("window.open('about:blank')"_string);
+ Core::EventLoop::current().spin_until([&]() { return popup != nullptr; });
+
+ popup->load_from_browser_ui(second_page_url);
+ Core::EventLoop::current().spin_until([&]() { return sandboxed_frame_process(*popup) != nullptr; });
+ auto& second_process = *sandboxed_frame_process(*popup);
+
+ EXPECT(&first_process != &second_process);
+ EXPECT_EQ(first_process.local_file_roots().size(), 1uz);
+ EXPECT_EQ(second_process.local_file_roots().size(), 1uz);
+}
+
+// Site isolation gives each root a process of its own, so a process refuses a second root rather than read under both.
+TEST_CASE(a_process_reads_local_files_under_one_root)
+{
+ Test::HeadlessTestEnvironment environment { "TestLocalFileNavigation"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ auto& process = view->page().client();
+
+ WebView::LocalFileRoot first { "/first"sv, WebView::LocalFileRoot::Scope::Directory };
+ WebView::LocalFileRoot second { "/second"sv, WebView::LocalFileRoot::Scope::Directory };
+ TRY_OR_FAIL(process.add_local_file_root(first));
+ TRY_OR_FAIL(process.add_local_file_root(first));
+ EXPECT(process.add_local_file_root(second).is_error());
+ EXPECT(process.local_file_roots() == Vector { first });
+}
diff --git a/Tests/LibWebView/TestLocalFileRoot.cpp b/Tests/LibWebView/TestLocalFileRoot.cpp
new file mode 100644
index 00000000000..5d30524ac28
--- /dev/null
+++ b/Tests/LibWebView/TestLocalFileRoot.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/LexicalPath.h>
+#include <LibCore/Directory.h>
+#include <LibCore/System.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibTest/TemporaryDirectory.h>
+#include <LibTest/TestCase.h>
+#include <LibWebView/LocalFileRoot.h>
+
+using Scope = WebView::LocalFileRoot::Scope;
+
+namespace {
+
+// A home directory holding a profile's cache, which a symbolic link reaches, and folders of the user's own.
+class TestHome {
+public:
+ TestHome()
+ : m_home(MUST(FileSystem::real_path(m_directory.path().string())))
+ {
+ MUST(Core::Directory::create(join("Documents/Project"sv), Core::Directory::CreateDirectories::Yes));
+ MUST(Core::Directory::create(join("Storage/Cache/Ladybird"sv), Core::Directory::CreateDirectories::Yes));
+ MUST(Core::System::symlink(join("Storage/Cache"sv), join(".cache"sv)));
+ }
+
+ ByteString join(StringView path) const { return LexicalPath::join(m_home, path).string(); }
+
+ WebView::LocalFileGrantPolicy policy(Optional<ByteString> root_for_tests = {}) const
+ {
+ return { m_home, { join(".cache/Ladybird"sv) }, move(root_for_tests) };
+ }
+
+private:
+ Test::TemporaryDirectory m_directory { "TestLocalFileRoot"sv };
+ ByteString m_home;
+};
+
+}
+
+TEST_CASE(roots_cover_what_is_under_them)
+{
+ WebView::LocalFileRoot directory { "/a/b"sv, Scope::Directory };
+ EXPECT(directory.covers("/a/b"sv));
+ EXPECT(directory.covers("/a/b/c.html"sv));
+ EXPECT(!directory.covers("/a/bc/d.html"sv));
+ EXPECT(!directory.covers("/a"sv));
+
+ WebView::LocalFileRoot file { "/a/b/c.html"sv, Scope::File };
+ EXPECT(file.covers("/a/b/c.html"sv));
+ EXPECT(!file.covers("/a/b/d.html"sv));
+ EXPECT(!file.covers("/a/b"sv));
+}
+
+TEST_CASE(a_file_the_user_opens_grants_its_folder)
+{
+ TestHome home;
+ auto policy = home.policy();
+
+ auto file = home.join("Documents/Project/index.html"sv);
+ EXPECT(policy.root_for_opened_file(file) == WebView::LocalFileRoot { home.join("Documents/Project"sv), Scope::Directory });
+ EXPECT(policy.root_for_opened_file("/srv/site/index.html"sv) == WebView::LocalFileRoot { "/srv/site"sv, Scope::Directory });
+}
+
+TEST_CASE(a_folder_that_is_too_wide_grants_only_the_file)
+{
+ TestHome home;
+ auto policy = home.policy();
+
+ // Home, and anything above it.
+ auto in_home = home.join("page.html"sv);
+ EXPECT(policy.root_for_opened_file(in_home) == WebView::LocalFileRoot { in_home, Scope::File });
+ EXPECT(policy.root_for_opened_file("/page.html"sv) == WebView::LocalFileRoot { "/page.html"sv, Scope::File });
+
+ // A folder holding the profile's directory, as named through a symbolic link.
+ auto beside_profile = home.join("Storage/Cache/page.html"sv);
+ EXPECT(policy.root_for_opened_file(beside_profile) == WebView::LocalFileRoot { beside_profile, Scope::File });
+
+ // The profile's directory itself: the file is all it grants, and nothing beside it.
+ auto in_profile = home.join("Storage/Cache/Ladybird/page.html"sv);
+ auto root = policy.root_for_opened_file(in_profile);
+ EXPECT(root == WebView::LocalFileRoot { in_profile, Scope::File });
+ EXPECT(!root.covers(home.join("Storage/Cache/Ladybird/Cookies.db"sv)));
+}
+
+TEST_CASE(a_test_root_is_granted_whole)
+{
+ TestHome home;
+ auto policy = home.policy(home.join("Documents"sv));
+
+ EXPECT(policy.root_for_opened_file(home.join("Documents/Project/index.html"sv)) == WebView::LocalFileRoot { home.join("Documents"sv), Scope::Directory });
+ EXPECT(policy.root_for_opened_file("/srv/site/index.html"sv) == WebView::LocalFileRoot { "/srv/site"sv, Scope::Directory });
+}
+
+TEST_CASE(a_saved_root_comes_back_only_if_still_allowed)
+{
+ TestHome home;
+ auto policy = home.policy();
+
+ WebView::LocalFileRoot folder { home.join("Documents/Project"sv), Scope::Directory };
+ EXPECT(policy.restore(folder) == folder);
+
+ // A file root comes back as it was, whatever is at its path now.
+ WebView::LocalFileRoot file { home.join("Documents/Project"sv), Scope::File };
+ EXPECT(policy.restore(file) == file);
+
+ // A folder that's no longer allowed is dropped, not narrowed to a file root that would cover nothing in it.
+ EXPECT(!policy.restore({ home.join("Storage"sv), Scope::Directory }).has_value());
+ EXPECT(!policy.restore({ home.join(""sv), Scope::Directory }).has_value());
+}
diff --git a/Tests/LibWebView/TestOpenLocalFileForRenderer.cpp b/Tests/LibWebView/TestOpenLocalFileForRenderer.cpp
index 50ddcda2cb2..ecbdcaf0f61 100644
--- a/Tests/LibWebView/TestOpenLocalFileForRenderer.cpp
+++ b/Tests/LibWebView/TestOpenLocalFileForRenderer.cpp
@@ -8,78 +8,157 @@
#include <AK/ScopeGuard.h>
#include <LibCore/File.h>
#include <LibCore/System.h>
+#include <LibFileSystem/FileSystem.h>
#include <LibTest/TemporaryDirectory.h>
#include <LibTest/TestCase.h>
#include <LibWebView/Utilities.h>
#include <sys/stat.h>
#include <unistd.h>
-static ByteString write_file(Test::TemporaryDirectory const& directory, StringView name, StringView content)
-{
- auto path = directory.path().append(name).string();
- auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));
- MUST(file->write_until_depleted(content));
- return path;
+namespace {
+
+class TestDirectory {
+public:
+ TestDirectory()
+ : m_root(MUST(FileSystem::real_path(m_directory.path().string())))
+ {
+ }
+
+ ByteString const& root() const { return m_root; }
+ ByteString join(StringView name) const { return LexicalPath::join(m_root, name).string(); }
+
+ ByteString write_file(StringView name, StringView content) const
+ {
+ auto path = join(name);
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));
+ MUST(file->write_until_depleted(content));
+ return path;
+ }
+
+ Vector<WebView::LocalFileRoot> roots() const { return { { m_root, WebView::LocalFileRoot::Scope::Directory } }; }
+
+private:
+ Test::TemporaryDirectory m_directory { "TestOpenLocalFileForRenderer"sv };
+ ByteString m_root;
+};
+
}
-static void expect_refused(ByteString const& path)
+static void expect_refused(ByteString const& path, ReadonlySpan<WebView::LocalFileRoot> roots)
{
- if (!WebView::open_local_file_for_renderer(path).is_error())
+ if (!WebView::open_local_file_for_renderer(path, roots).is_error())
FAIL(ByteString::formatted("{} was opened", path));
}
-TEST_CASE(regular_files_and_directories_open)
+TEST_CASE(files_under_a_root_open)
{
- Test::TemporaryDirectory directory { "TestOpenLocalFileForRenderer"sv };
- auto file_path = write_file(directory, "file.txt"sv, "content"sv);
+ TestDirectory directory;
+ auto file_path = directory.write_file("file.txt"sv, "content"sv);
- TRY_OR_FAIL(WebView::open_local_file_for_renderer(file_path));
- TRY_OR_FAIL(WebView::open_local_file_for_renderer(directory.path().string()));
+ TRY_OR_FAIL(WebView::open_local_file_for_renderer(file_path, directory.roots()));
+ TRY_OR_FAIL(WebView::open_local_file_for_renderer(directory.root(), directory.roots()));
- auto link_path = directory.path().append("link.txt"sv).string();
+ // A link inside the root to a file inside it reaches the file.
+ auto link_path = directory.join("link.txt"sv);
TRY_OR_FAIL(Core::System::symlink(file_path, link_path));
- auto linked = TRY_OR_FAIL(WebView::open_local_file_for_renderer(link_path));
- auto linked_file = TRY_OR_FAIL(Core::File::adopt_fd(linked.take_fd(), Core::File::OpenMode::Read));
+ auto linked = TRY_OR_FAIL(WebView::open_local_file_for_renderer(link_path, directory.roots()));
+ EXPECT_EQ(linked.canonical_path, file_path);
+ auto linked_file = TRY_OR_FAIL(Core::File::adopt_fd(linked.file.take_fd(), Core::File::OpenMode::Read));
auto content = TRY_OR_FAIL(linked_file->read_until_eof());
EXPECT_EQ(StringView { content }, "content"sv);
}
+TEST_CASE(files_outside_the_roots_are_refused)
+{
+ TestDirectory directory;
+ TestDirectory other_directory;
+ auto other_file = other_directory.write_file("file.txt"sv, "content"sv);
+ expect_refused(other_file, directory.roots());
+ TRY_OR_FAIL(WebView::open_local_file_the_user_chose(other_file));
+
+ // A link inside the root leads only to what's inside it too.
+ auto link_path = directory.join("link"sv);
+ TRY_OR_FAIL(Core::System::symlink(other_file, link_path));
+ expect_refused(link_path, directory.roots());
+
+ // As does a path that leaves the root and comes back elsewhere.
+ expect_refused(ByteString::formatted("{}/../{}/file.txt", directory.root(), LexicalPath::basename(other_directory.root())), directory.roots());
+
+ expect_refused("/etc/hosts"sv, directory.roots());
+ expect_refused(directory.root(), {});
+}
+
+TEST_CASE(a_file_root_covers_only_its_file)
+{
+ TestDirectory directory;
+ auto file_path = directory.write_file("file.txt"sv, "content"sv);
+ auto sibling_path = directory.write_file("sibling.txt"sv, "content"sv);
+
+ Vector<WebView::LocalFileRoot> roots { { file_path, WebView::LocalFileRoot::Scope::File } };
+ TRY_OR_FAIL(WebView::open_local_file_for_renderer(file_path, roots));
+ expect_refused(sibling_path, roots);
+ expect_refused(directory.root(), roots);
+}
+
TEST_CASE(other_kinds_of_file_are_refused)
{
- Test::TemporaryDirectory directory { "TestOpenLocalFileForRenderer"sv };
+ TestDirectory directory;
- auto fifo_path = directory.path().append("fifo"sv).string();
+ auto fifo_path = directory.join("fifo"sv);
VERIFY(mkfifo(fifo_path.characters(), 0600) == 0);
- expect_refused(fifo_path);
+ expect_refused(fifo_path, directory.roots());
- auto link_path = directory.path().append("link"sv).string();
+ auto link_path = directory.join("link"sv);
TRY_OR_FAIL(Core::System::symlink(fifo_path, link_path));
- expect_refused(link_path);
+ expect_refused(link_path, directory.roots());
- expect_refused("/dev/null"sv);
+ if (!WebView::open_local_file_the_user_chose("/dev/null"sv).is_error())
+ FAIL("/dev/null was opened");
+}
+
+// A descriptor link reaches a file this process has open, wherever that file is.
+TEST_CASE(descriptor_links_reach_only_files_under_the_roots)
+{
+ TestDirectory directory;
+ TestDirectory other_directory;
+ auto other_path = other_directory.write_file("file.txt"sv, "content"sv);
+ auto other_file = TRY_OR_FAIL(Core::File::open(other_path, Core::File::OpenMode::Read));
+
+ auto descriptor_path = ByteString::formatted("/dev/fd/{}", other_file->fd());
+ expect_refused(descriptor_path, directory.roots());
+
+ auto link_path = directory.join("link"sv);
+ TRY_OR_FAIL(Core::System::symlink(descriptor_path, link_path));
+ expect_refused(link_path, directory.roots());
}
#if defined(AK_OS_MACOS)
-// A /dev/fd entry opens a descriptor of this process, which reads as the file behind it. realpath() turns /dev/fd/N into
-// /dev/fd/ and the file's name, so the file is named after its descriptor.
+// A /dev/fd entry reads as the file behind it, so it's refused even under a root that covers it, and even when the user
+// chose it. realpath() turns /dev/fd/N into /dev/fd/ and the file's name, so the file is named after its descriptor.
TEST_CASE(descriptor_entries_are_refused)
{
static constexpr int descriptor = 900;
// macOS starts a process with a limit of 256 descriptors.
TRY_OR_FAIL(Core::System::set_resource_limits(RLIMIT_NOFILE, 65536));
- Test::TemporaryDirectory directory { "TestOpenLocalFileForRenderer"sv };
- auto file = TRY_OR_FAIL(Core::File::open(write_file(directory, ByteString::number(descriptor), "content"sv), Core::File::OpenMode::Read));
- VERIFY(dup2(file->fd(), descriptor) == descriptor);
+ TestDirectory other_directory;
+ auto other_file = TRY_OR_FAIL(Core::File::open(other_directory.write_file(ByteString::number(descriptor), "content"sv), Core::File::OpenMode::Read));
+ VERIFY(dup2(other_file->fd(), descriptor) == descriptor);
ScopeGuard close_descriptor = [] { close(descriptor); };
- expect_refused(ByteString::formatted("/dev/fd/{}", descriptor));
+ auto descriptor_path = ByteString::formatted("/dev/fd/{}", descriptor);
+
+ Vector<WebView::LocalFileRoot> roots { { "/dev/fd"sv, WebView::LocalFileRoot::Scope::Directory } };
+ expect_refused(descriptor_path, roots);
+ if (!WebView::open_local_file_the_user_chose(descriptor_path).is_error())
+ FAIL(ByteString::formatted("{} was opened", descriptor_path));
}
#endif
#if defined(AK_OS_LINUX)
TEST_CASE(process_and_system_information_is_refused)
{
- expect_refused("/proc/self/maps"sv);
- expect_refused("/proc/self/environ"sv);
- expect_refused("/sys/kernel/mm/transparent_hugepage/enabled"sv);
+ for (auto path : { "/proc/self/maps"sv, "/proc/self/environ"sv, "/sys/kernel/mm/transparent_hugepage/enabled"sv }) {
+ if (!WebView::open_local_file_the_user_chose(path).is_error())
+ FAIL(ByteString::formatted("{} was opened", path));
+ }
}
#endif
diff --git a/Tests/LibWebView/TestRendererResponseBodyClaims.cpp b/Tests/LibWebView/TestRendererResponseBodyClaims.cpp
index a40bea2ef95..92ad00a99c3 100644
--- a/Tests/LibWebView/TestRendererResponseBodyClaims.cpp
+++ b/Tests/LibWebView/TestRendererResponseBodyClaims.cpp
@@ -12,6 +12,7 @@
#include <LibCore/File.h>
#include <LibCore/Socket.h>
#include <LibCore/TCPServer.h>
+#include <LibFileSystem/FileSystem.h>
#include <LibGfx/SystemTheme.h>
#include <LibHTTP/HeaderList.h>
#include <LibRequests/Request.h>
@@ -613,9 +614,9 @@ TEST_CASE(made_up_file_url_does_not_reach_a_navigation)
}
// The process running a navigation's population steps can host web content, so it does not read the local file that a
-// file: URL names. The UI process reads the file of a navigation it admitted, or of an entry whose document state held
-// local file content, for the process creating the document. It reads no other file, and ignores any body the process
-// reports.
+// file: URL names. The UI process reads the file of a navigation it admitted, the user's choice or one under the roots
+// the navigation came with, for the process creating the document. It reads no other file, and ignores any body the
+// process reports.
TEST_CASE(ui_process_reads_the_local_file_of_a_navigation)
{
TestFixture fixture;
@@ -630,8 +631,8 @@ TEST_CASE(ui_process_reads_the_local_file_of_a_navigation)
auto local_file_url = write_file("local.html"sv, "<p>The local file.</p>"sv);
auto other_local_file_url = write_file("other.html"sv, "<p>Another local file.</p>"sv);
- auto acquire = [&](WebView::NavigationLoader::MayReadLocalFile may_read_local_file, Function<void(Web::HTML::NavigationParamsDescriptor&)> report) {
- auto loader = WebView::NavigationLoader::create(population_request_for(*view, local_file_url, Utf16String::from_utf8(generate_random_uuid())), may_read_local_file);
+ auto acquire = [&](WebView::LocalFileAccess local_file_access, Function<void(Web::HTML::NavigationParamsDescriptor&)> report) {
+ auto loader = WebView::NavigationLoader::create(population_request_for(*view, local_file_url, Utf16String::from_utf8(generate_random_uuid())), move(local_file_access));
auto result = result_with_response_body_of(0, 0);
auto& navigation_params = result.navigation_params.get<Web::HTML::NavigationParamsDescriptor>();
navigation_params.response.url_list = { local_file_url };
@@ -647,17 +648,24 @@ TEST_CASE(ui_process_reads_the_local_file_of_a_navigation)
return loader->take_result().navigation_params;
};
- auto navigation_params = acquire(WebView::NavigationLoader::MayReadLocalFile::Yes, [](auto&) { });
+ auto navigation_params = acquire(WebView::UserSelectedLocalFile {}, [](auto&) { });
VERIFY(navigation_params.has<Web::HTML::NavigationParamsDescriptor>());
auto const& response = navigation_params.get<Web::HTML::NavigationParamsDescriptor>().response;
EXPECT_EQ(StringView { response.body.get<ByteBuffer>() }, "<p>The local file.</p>"sv);
EXPECT_EQ(HTTP::HeaderList::create(response.headers)->get("Content-Type"sv).value_or({}), "text/html"sv);
- // An entry whose document state held no local file content gets an error document.
- EXPECT(acquire(WebView::NavigationLoader::MayReadLocalFile::No, [](auto&) { }).has<Web::HTML::NavigationParamsNullOrError>());
+ // A navigation under a root that covers the file reads it too.
+ auto directory = MUST(FileSystem::real_path(fixture.directory()));
+ Vector<WebView::LocalFileRoot> covering_roots { { directory, WebView::LocalFileRoot::Scope::Directory } };
+ EXPECT(acquire(covering_roots, [](auto&) { }).has<Web::HTML::NavigationParamsDescriptor>());
+
+ // A navigation with no local file access gets an error document, as does one under roots that don't cover the file.
+ EXPECT(acquire({}, [](auto&) { }).has<Web::HTML::NavigationParamsNullOrError>());
+ Vector<WebView::LocalFileRoot> other_roots { { LexicalPath::join(directory, "other.html"sv).string(), WebView::LocalFileRoot::Scope::File } };
+ EXPECT(acquire(other_roots, [](auto&) { }).has<Web::HTML::NavigationParamsNullOrError>());
// So does a navigation whose response the process reports for another local file.
- EXPECT(acquire(WebView::NavigationLoader::MayReadLocalFile::Yes, [&](auto& navigation_params) {
+ EXPECT(acquire(WebView::UserSelectedLocalFile {}, [&](auto& navigation_params) {
navigation_params.response.url_list = { other_local_file_url };
}).has<Web::HTML::NavigationParamsNullOrError>());
EXPECT(view->page().client().is_open());
diff --git a/Tests/LibWebView/TestSessionHistory.cpp b/Tests/LibWebView/TestSessionHistory.cpp
index 88389682ab1..c6d615337c9 100644
--- a/Tests/LibWebView/TestSessionHistory.cpp
+++ b/Tests/LibWebView/TestSessionHistory.cpp
@@ -1111,23 +1111,25 @@ TEST_CASE(restore_from_ui_snapshot_preserves_shared_document_state_identity)
EXPECT_EQ(first_id, second_id);
}
-// The browser reads the local file an entry names for a history step only when it populated local file content for the
-// entry's document state, so a restored document state keeps that under its new identity.
-TEST_CASE(restore_from_ui_snapshot_keeps_which_document_states_held_local_file_content)
+// The browser reads the local file an entry names for a history step only under the root of the local file content it
+// populated for the entry's document state, so a restored document state keeps that root under its new identity.
+TEST_CASE(restore_from_ui_snapshot_keeps_the_local_file_roots_of_document_states)
{
WebView::TraversableSessionHistory history { initial_history_entry() };
+ WebView::LocalFileRoot root { "/tmp/a.html"sv, WebView::LocalFileRoot::Scope::File };
+ WebView::LocalFileRoot unused_root { "/tmp"sv, WebView::LocalFileRoot::Scope::Directory };
auto result = history.restore_from_ui_snapshot({
entry(0, "file:///tmp/a.html"sv, 1, "main"sv),
entry(1, "https://a.example/"sv, 2, "main"sv),
},
- { 0, 1 }, 1, allocate_test_ui_process_document_state_id, { test_document_state_id(1), test_document_state_id(7) });
+ { 0, 1 }, 1, allocate_test_ui_process_document_state_id, { { test_document_state_id(1), root }, { test_document_state_id(7), unused_root } });
EXPECT(!result.is_error());
auto const& file_document_state = *history.entry_at(0)->document_state;
- EXPECT(file_document_state.held_local_file_content);
- EXPECT(!history.entry_at(1)->document_state->held_local_file_content);
- EXPECT(history.document_states_holding_local_file_content() == Vector<Web::HTML::CrossProcessId> { file_document_state.id });
+ EXPECT(file_document_state.local_file_root == root);
+ EXPECT(!history.entry_at(1)->document_state->local_file_root.has_value());
+ EXPECT(history.local_file_roots_of_document_states() == Vector<WebView::DocumentStateLocalFileRoot> { { file_document_state.id, root } });
}
TEST_CASE(restore_from_ui_snapshot_rejects_structurally_invalid_snapshots)
diff --git a/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp b/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
index a21afa586ec..56d04c4afad 100644
--- a/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
+++ b/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
@@ -354,7 +354,7 @@ static void insert_minimal_entry(Database::Database& database, SessionHistorySna
static_cast<i64>(0), absent_text, absent_text, absent_text, absent_port, absent_text,
static_cast<i64>(0), absent_text, static_cast<i64>(0),
static_cast<i64>(0), absent_text,
- absent_text, String {}, ever_populated, false, false, false);
+ absent_text, String {}, ever_populated, false, false, absent_text, Optional<i64> {});
}
static i32 count_tab_rows(Database::Database& database, StringView table, i64 tab_id)
@@ -545,9 +545,9 @@ TEST_CASE(snapshot_round_trips_flat_entries)
EXPECT_EQ(loaded.entries[1].document_state.initiator_origin->domain()->serialize(), "b.example"_string);
}
-// The document states the browser populated local file content for survive a round trip, including in nested
-// histories, and a document state that several entries share is named once.
-TEST_CASE(snapshot_round_trip_preserves_document_states_holding_local_file_content)
+// The roots of the local file content the browser populated for document states survive a round trip, with their
+// scopes, including in nested histories, and a document state that several entries share is named once.
+TEST_CASE(snapshot_round_trip_preserves_the_local_file_roots_of_document_states)
{
auto database = make_database();
auto statements = prepare_snapshot_tables(*database);
@@ -566,12 +566,48 @@ TEST_CASE(snapshot_round_trip_preserves_document_states_holding_local_file_conte
snapshot.entries.append(make_entry(2, "file:///tmp/parent.html#again"sv, 1, 0x77, 0x88, "keyD"sv, "idD"sv, {}));
snapshot.used_steps = { 0, 1, 2 };
snapshot.current_used_step_index = 2;
- snapshot.document_states_holding_local_file_content = { snapshot.entries[0].document_state.id, snapshot.entries[0].document_state.nested_histories[0].entries[0].document_state.id };
+ snapshot.local_file_roots_of_document_states = {
+ { snapshot.entries[0].document_state.id, { "/tmp"sv, WebView::LocalFileRoot::Scope::Directory } },
+ { snapshot.entries[0].document_state.nested_histories[0].entries[0].document_state.id, { "/tmp/child.html"sv, WebView::LocalFileRoot::Scope::File } },
+ };
TRY_OR_FAIL(store_session_history_snapshot(*database, statements, 43, snapshot));
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, statements, 43, 2));
- EXPECT(loaded.document_states_holding_local_file_content == snapshot.document_states_holding_local_file_content);
+ EXPECT(loaded.local_file_roots_of_document_states == snapshot.local_file_roots_of_document_states);
+}
+
+// A database from before local file roots marked the entries that held local file content, and those come back with no
+// root.
+TEST_CASE(snapshot_entries_that_held_local_file_content_load_without_a_root)
+{
+ auto database = make_database();
+ auto statements = prepare_snapshot_tables(*database);
+
+ insert_tab_row(*database, 44);
+
+ WebView::SessionHistorySnapshot snapshot;
+ snapshot.entries.append(make_entry(0, "file:///tmp/a.html"sv, 1, 0x11, 0x22, "keyA"sv, "idA"sv, {}));
+ snapshot.used_steps = { 0 };
+ snapshot.current_used_step_index = 0;
+
+ TRY_OR_FAIL(store_session_history_snapshot(*database, statements, 44, snapshot));
+
+ // Take the database back to the schema before local file roots, with the entry marked as holding local file content.
+ TRY_OR_FAIL(database->execute_raw(R"#(
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_scope;
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_path;
+ ALTER TABLE SessionEntries ADD COLUMN held_local_file_content INTEGER NOT NULL DEFAULT 0;
+ UPDATE SessionEntries SET held_local_file_content = 1;
+ UPDATE SchemaVersions SET version = 11 WHERE store = 'Sessions';
+ )#"sv));
+
+ auto migrated_statements = prepare_snapshot_tables(*database);
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 12u });
+
+ auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 44, 0));
+ EXPECT_EQ(loaded.entries.size(), 1uz);
+ EXPECT(loaded.local_file_roots_of_document_states.is_empty());
}
// A database from before the user_agent_initiated column gains it with every entry saved there as No.
@@ -594,7 +630,8 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
// Take the database back to the baseline schema, keeping the entry's row.
TRY_OR_FAIL(database->execute_raw(R"#(
- ALTER TABLE SessionEntries DROP COLUMN held_local_file_content;
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_scope;
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_path;
DROP TABLE SessionUpgradeInsecureNavigations;
ALTER TABLE SessionPolicyContainers DROP COLUMN insecure_requests_policy;
ALTER TABLE Sessions DROP COLUMN maximized;
@@ -615,7 +652,7 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 11u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 12u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 42, 0));
EXPECT_EQ(loaded.entries.size(), 1uz);
@@ -644,7 +681,8 @@ TEST_CASE(snapshot_policy_containers_saved_before_the_insecure_requests_policy_l
// Take the database back to the schema before the insecure requests policy, keeping the container's row.
TRY_OR_FAIL(database->execute_raw(R"#(
- ALTER TABLE SessionEntries DROP COLUMN held_local_file_content;
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_scope;
+ ALTER TABLE SessionEntries DROP COLUMN local_file_root_path;
DROP TABLE SessionUpgradeInsecureNavigations;
ALTER TABLE SessionPolicyContainers DROP COLUMN insecure_requests_policy;
ALTER TABLE SessionLifecycle DROP COLUMN restart;
@@ -652,7 +690,7 @@ TEST_CASE(snapshot_policy_containers_saved_before_the_insecure_requests_policy_l
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 11u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 12u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 27, 0));
auto const* container = loaded.entries[0].document_state.history_policy_container.get_pointer<Web::HTML::SerializedPolicyContainer>();
@@ -956,6 +994,27 @@ TEST_CASE(snapshot_store_rejects_oversized_snapshot)
EXPECT_EQ(count_history_owned_rows(*database, "SessionEntries"sv, 25), 0);
}
+// Each entry of a document state stores its root's path, so a snapshot that loading would refuse is never stored.
+TEST_CASE(snapshot_store_counts_a_shared_local_file_root_path_per_entry)
+{
+ auto database = make_database();
+ auto statements = prepare_snapshot_tables(*database);
+
+ WebView::SessionHistorySnapshot snapshot;
+ for (i32 step = 0; step < 9; ++step) {
+ snapshot.entries.append(make_entry(step, "file:///tmp/a.html"sv, 1, 0, 0, ""sv, ""sv, {}));
+ snapshot.used_steps.append(step);
+ }
+ snapshot.current_used_step_index = snapshot.used_steps.size() - 1;
+ auto path = ByteString::formatted("/{}", ByteString::repeated('a', (8uz * 1024 * 1024) - 1));
+ snapshot.local_file_roots_of_document_states.append({ snapshot.entries[0].document_state.id, { path, WebView::LocalFileRoot::Scope::Directory } });
+
+ auto result = store_session_history_snapshot(*database, statements, 25, snapshot);
+ EXPECT(result.is_error());
+ EXPECT_EQ(result.error().string_literal(), "Session history snapshot exceeds the maximum size"sv);
+ EXPECT_EQ(count_history_owned_rows(*database, "SessionEntries"sv, 25), 0);
+}
+
TEST_CASE(snapshot_store_rolls_back_with_the_caller_transaction)
{
auto database = make_database();
diff --git a/Tests/UI/Qt/TestSessionStore.cpp b/Tests/UI/Qt/TestSessionStore.cpp
index aa8c6200bf3..fe4d20a0c8c 100644
--- a/Tests/UI/Qt/TestSessionStore.cpp
+++ b/Tests/UI/Qt/TestSessionStore.cpp
@@ -79,7 +79,8 @@ static SessionTabId open_tab(SessionStore& store, SessionWindowId window, String
// Takes the schema back to SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION, so every migration after it runs again.
static void rewind_sessions_schema_to_version_4(Database::Database& database)
{
- MUST(database.execute_raw("ALTER TABLE SessionEntries DROP COLUMN held_local_file_content;"sv));
+ MUST(database.execute_raw("ALTER TABLE SessionEntries DROP COLUMN local_file_root_scope;"sv));
+ MUST(database.execute_raw("ALTER TABLE SessionEntries DROP COLUMN local_file_root_path;"sv));
MUST(database.execute_raw("DROP TABLE SessionUpgradeInsecureNavigations;"sv));
MUST(database.execute_raw("ALTER TABLE SessionPolicyContainers DROP COLUMN insecure_requests_policy;"sv));
MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN maximized;"sv));
@@ -111,7 +112,7 @@ TEST_CASE(fresh_database_migrates_to_the_latest_schema)
for (auto table : { "Sessions"sv, "SessionTabs"sv, "SessionUsedSteps"sv, "SessionHistories"sv, "SessionNestedHistories"sv, "SessionEntries"sv, "SessionUpgradeInsecureNavigations"sv })
EXPECT(TRY_OR_FAIL(database->table_exists(table)));
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 11u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 12u });
}
TEST_CASE(deleting_a_session_cascades_through_its_tabs)
@@ -158,7 +159,7 @@ TEST_CASE(version_4_database_migrates_to_the_latest_schema)
rewind_sessions_schema_to_version_4(*database);
EXPECT_EQ(TRY_OR_FAIL(SessionStore::migrate_schema(*database)), Database::MigrationOutcome::Success);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 11u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 12u });
EXPECT(TRY_OR_FAIL(database->table_exists("SessionUpgradeInsecureNavigations"sv)));
EXPECT_EQ(select_i64(*database, "SELECT pinned FROM SessionTabs WHERE id = 2;"_string), 0);
EXPECT_EQ(select_i64(*database, "SELECT COUNT(*) FROM Sessions WHERE id = 1 AND width IS NULL;"_string), 1);
@@ -225,7 +226,7 @@ TEST_CASE(a_changed_user_agent_initiated_flag_alone_flushes)
EXPECT_EQ(select_i64(*database, "SELECT COUNT(*) FROM SessionEntries WHERE user_agent_initiated = 1;"_string), 1);
}
-TEST_CASE(a_changed_set_of_document_states_holding_local_file_content_alone_replaces_a_pending_push)
+TEST_CASE(a_changed_set_of_local_file_roots_alone_replaces_a_pending_push)
{
auto database = create_session_database();
auto store = TRY_OR_FAIL(SessionStore::create(*database));
@@ -236,10 +237,10 @@ TEST_CASE(a_changed_set_of_document_states_holding_local_file_content_alone_repl
store->update_tab_state({ .tab_id = tab, .history = snapshot, .url = parse_url("file:///tmp/a.html"sv) });
// The set is the only difference from the pending push, which it still replaces.
- snapshot.document_states_holding_local_file_content.append(snapshot.entries[0].document_state.id);
+ snapshot.local_file_roots_of_document_states.append({ snapshot.entries[0].document_state.id, { "/tmp"sv, WebView::LocalFileRoot::Scope::Directory } });
store->update_tab_state({ .tab_id = tab, .history = snapshot, .url = parse_url("file:///tmp/a.html"sv) });
store->flush_dirty_state();
- EXPECT_EQ(select_i64(*database, "SELECT COUNT(*) FROM SessionEntries WHERE held_local_file_content = 1;"_string), 1);
+ EXPECT_EQ(select_i64(*database, "SELECT COUNT(*) FROM SessionEntries WHERE local_file_root_path = '/tmp';"_string), 1);
}
TEST_CASE(a_changed_insecure_requests_policy_alone_replaces_a_pending_push)
diff --git a/UI/Qt/ContextMenus.cpp b/UI/Qt/ContextMenus.cpp
index a372c688016..520ab3d3054 100644
--- a/UI/Qt/ContextMenus.cpp
+++ b/UI/Qt/ContextMenus.cpp
@@ -347,8 +347,9 @@ static NonnullRefPtr<Menu> create_media_context_menu(RemoteView& view, ContextMe
menu->add_separator();
if (media.media_url.has_value()) {
auto url = *media.media_url;
- add_open_in_new_tab_action(*menu, view_id, media.is_video ? "Open Video in New Tab"sv : "Open Audio in New Tab"sv, url, request.navigation);
+ // NB: The page controls the media URL, so it's opened only as a navigation from the page.
if (request.navigation.has_value()) {
+ add_open_in_new_tab_action(*menu, view_id, media.is_video ? "Open Video in New Tab"sv : "Open Audio in New Tab"sv, url, request.navigation);
menu->add_action(Action::create(media.is_video ? "Open Video"sv : "Open Audio"sv, media.is_video ? ActionID::OpenVideo : ActionID::OpenAudio, on_view(view_id, [navigation = *request.navigation](RemoteView& view) {
view.load(navigation);
})));
diff --git a/UI/Qt/SessionHistorySnapshotStorage.cpp b/UI/Qt/SessionHistorySnapshotStorage.cpp
index 9c9d7459b04..90121537e9d 100644
--- a/UI/Qt/SessionHistorySnapshotStorage.cpp
+++ b/UI/Qt/SessionHistorySnapshotStorage.cpp
@@ -516,7 +516,28 @@ static ErrorOr<void> validate_persisted_origin_within_caps(PersistedOrigin const
return {};
}
-static ErrorOr<void> validate_entry_within_column_caps(Web::HTML::SessionHistoryEntryDescriptor const& entry, SnapshotRowTotals& totals)
+using LocalFileRootsByDocumentState = HashMap<Web::HTML::CrossProcessId, WebView::LocalFileRoot>;
+
+static LocalFileRootsByDocumentState local_file_roots_by_document_state(WebView::SessionHistorySnapshot const& snapshot)
+{
+ LocalFileRootsByDocumentState local_file_roots;
+ for (auto const& [id, root] : snapshot.local_file_roots_of_document_states)
+ local_file_roots.set(id, root);
+ return local_file_roots;
+}
+
+// NB: A root whose path isn't UTF-8 isn't kept, so its document state comes back without one.
+static Optional<String> stored_local_file_root_path(LocalFileRootsByDocumentState const& local_file_roots, Web::HTML::CrossProcessId document_state_id)
+{
+ auto root = local_file_roots.get(document_state_id);
+ if (!root.has_value())
+ return {};
+ if (auto path = String::from_byte_string(root->path); !path.is_error())
+ return path.release_value();
+ return {};
+}
+
+static ErrorOr<void> validate_entry_within_column_caps(Web::HTML::SessionHistoryEntryDescriptor const& entry, LocalFileRootsByDocumentState const& local_file_roots, SnapshotRowTotals& totals)
{
auto const& document_state = entry.document_state;
@@ -539,6 +560,7 @@ static ErrorOr<void> validate_entry_within_column_caps(Web::HTML::SessionHistory
TRY(validate_persisted_origin_within_caps(encode_origin(document_state.initiator_origin), totals));
TRY(validate_text_column_within_cap(encode_referrer(document_state.request_referrer).url, totals));
TRY(validate_text_column_within_cap(encode_resource(document_state.resource).string, totals));
+ TRY(validate_text_column_within_cap(stored_local_file_root_path(local_file_roots, document_state.id), totals));
if (auto const* container = document_state.history_policy_container.get_pointer<Web::HTML::SerializedPolicyContainer>()) {
TRY(validate_text_column_within_cap(container->embedder_policy.reporting_endpoint, totals));
@@ -584,7 +606,7 @@ ErrorOr<SessionHistorySnapshotStatements> prepare_session_history_snapshot_state
initiator_origin_host, initiator_origin_port, initiator_origin_domain,
referrer_kind, referrer_url, referrer_policy, resource_kind, resource_string,
about_base_url, navigable_target_name, ever_populated, reload_pending, user_agent_initiated,
- held_local_file_content)
+ local_file_root_path, local_file_root_scope)
VALUES (
:history_id, :entry_ordinal, :step, :url, :document_state_namespace_id, :document_state_local_id,
:classic_state, :navigation_state,
@@ -596,7 +618,7 @@ ErrorOr<SessionHistorySnapshotStatements> prepare_session_history_snapshot_state
:initiator_origin_host, :initiator_origin_port, :initiator_origin_domain,
:referrer_kind, :referrer_url, :referrer_policy, :resource_kind, :resource_string,
:about_base_url, :navigable_target_name, :ever_populated, :reload_pending, :user_agent_initiated,
- :held_local_file_content);
+ :local_file_root_path, :local_file_root_scope);
)#"sv)),
.insert_used_step = TRY(database.prepare_statement(
"INSERT INTO SessionUsedSteps (tab_id, step_ordinal, step) VALUES (:tab_id, :step_ordinal, :step);"sv)),
@@ -649,7 +671,7 @@ ErrorOr<SessionHistorySnapshotStatements> prepare_session_history_snapshot_state
initiator_origin_host, initiator_origin_port, initiator_origin_domain,
referrer_kind, referrer_url, referrer_policy, resource_kind, resource_string,
about_base_url, navigable_target_name, ever_populated, reload_pending, user_agent_initiated,
- held_local_file_content
+ local_file_root_path, local_file_root_scope
FROM SessionEntries
INNER JOIN SessionHistories ON SessionEntries.history_id = SessionHistories.id
WHERE SessionHistories.tab_id = :tab_id;
@@ -795,14 +817,14 @@ static ErrorOr<void> store_policy_container(Database::Database& database, Sessio
return {};
}
-static ErrorOr<void> validate_entries_storable(Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, size_t depth, SnapshotRowTotals& totals)
+static ErrorOr<void> validate_entries_storable(Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, LocalFileRootsByDocumentState const& local_file_roots, size_t depth, SnapshotRowTotals& totals)
{
if (depth > WebView::MAX_NESTED_HISTORY_DEPTH)
return Error::from_string_literal("Session history nests deeper than the supported budget");
for (auto const& entry : entries) {
auto const& document_state = entry.document_state;
- TRY(validate_entry_within_column_caps(entry, totals));
+ TRY(validate_entry_within_column_caps(entry, local_file_roots, totals));
if (++totals.entries > MAX_SNAPSHOT_ENTRIES)
return Error::from_string_literal("Session history snapshot has more entries than the supported budget");
@@ -829,7 +851,7 @@ static ErrorOr<void> validate_entries_storable(Vector<Web::HTML::SessionHistoryE
for (auto const& nested_history : document_state.nested_histories) {
if (++totals.histories > MAX_SNAPSHOT_HISTORIES)
return Error::from_string_literal("Session history snapshot has more histories than the supported budget");
- TRY(validate_entries_storable(nested_history.entries, depth + 1, totals));
+ TRY(validate_entries_storable(nested_history.entries, local_file_roots, depth + 1, totals));
}
}
@@ -839,11 +861,11 @@ static ErrorOr<void> validate_entries_storable(Vector<Web::HTML::SessionHistoryE
ErrorOr<void> validate_session_history_snapshot_storable(WebView::SessionHistorySnapshot const& snapshot)
{
SnapshotRowTotals totals;
- TRY(validate_entries_storable(snapshot.entries, 0, totals));
+ TRY(validate_entries_storable(snapshot.entries, local_file_roots_by_document_state(snapshot), 0, totals));
return WebView::validate_snapshot_is_restorable(snapshot.entries, snapshot.used_steps, snapshot.current_used_step_index);
}
-static ErrorOr<void> store_history_entries(Database::Database& database, SessionHistorySnapshotStatements const& statements, i64 tab_id, i64 history_id, Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, HashTable<Web::HTML::CrossProcessId> const& document_states_holding_local_file_content)
+static ErrorOr<void> store_history_entries(Database::Database& database, SessionHistorySnapshotStatements const& statements, i64 tab_id, i64 history_id, Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, LocalFileRootsByDocumentState const& local_file_roots)
{
i64 entry_ordinal = 0;
for (auto const& entry : entries) {
@@ -854,6 +876,10 @@ static ErrorOr<void> store_history_entries(Database::Database& database, Session
auto referrer = encode_referrer(document_state.request_referrer);
auto resource = encode_resource(document_state.resource);
auto about_base_url = document_state.about_base_url.map([](auto const& url) { return url.serialize(); });
+ auto local_file_root_path = stored_local_file_root_path(local_file_roots, document_state.id);
+ Optional<i64> local_file_root_scope;
+ if (local_file_root_path.has_value())
+ local_file_root_scope = to_underlying(local_file_roots.get(document_state.id)->scope);
TRY(database.try_execute_bound_statement(statements.insert_entry, [&](auto& bind) -> ErrorOr<void> {
TRY(bind("history_id"sv, history_id));
@@ -894,7 +920,8 @@ static ErrorOr<void> store_history_entries(Database::Database& database, Session
TRY(bind("ever_populated"sv, document_state.ever_populated));
TRY(bind("reload_pending"sv, document_state.reload_pending));
TRY(bind("user_agent_initiated"sv, document_state.user_agent_initiated == Web::HTML::UserAgentInitiated::Yes));
- TRY(bind("held_local_file_content"sv, document_states_holding_local_file_content.contains(document_state.id)));
+ TRY(bind("local_file_root_path"sv, local_file_root_path));
+ TRY(bind("local_file_root_scope"sv, local_file_root_scope));
return {};
}));
++entry_ordinal;
@@ -920,7 +947,7 @@ static ErrorOr<void> store_history_entries(Database::Database& database, Session
TRY(bind("child_history_id"sv, child_history_id));
return {};
}));
- TRY(store_history_entries(database, statements, tab_id, child_history_id, nested_history.entries, document_states_holding_local_file_content));
+ TRY(store_history_entries(database, statements, tab_id, child_history_id, nested_history.entries, local_file_roots));
++nested_ordinal;
}
++entry_ordinal;
@@ -947,10 +974,7 @@ ErrorOr<void> store_session_history_snapshot(Database::Database& database, Sessi
auto root_history_id = TRY(insert_row_returning_id(database, statements.insert_history, [&](auto& bind) -> ErrorOr<void> {
return bind("tab_id"sv, tab_id);
}));
- HashTable<Web::HTML::CrossProcessId> document_states_holding_local_file_content;
- for (auto id : snapshot.document_states_holding_local_file_content)
- document_states_holding_local_file_content.set(id);
- TRY(store_history_entries(database, statements, tab_id, root_history_id, snapshot.entries, document_states_holding_local_file_content));
+ TRY(store_history_entries(database, statements, tab_id, root_history_id, snapshot.entries, local_file_roots_by_document_state(snapshot)));
return {};
}
@@ -984,7 +1008,7 @@ struct EntryRow {
bool ever_populated { false };
bool reload_pending { false };
bool user_agent_initiated { false };
- bool held_local_file_content { false };
+ Optional<WebView::LocalFileRoot> local_file_root;
};
struct PolicyContainerRow {
@@ -1340,8 +1364,8 @@ struct HistoryTreeLoadState {
HashMap<i64, Vector<NestedHistoryLinkRow>> links_by_parent;
HashMap<i64, HashMap<i64, Web::HTML::SerializedPolicyContainer>> containers_by_history;
HashTable<i64> unvisited_histories;
- Vector<Web::HTML::CrossProcessId> document_states_holding_local_file_content;
- HashTable<Web::HTML::CrossProcessId> seen_document_states_holding_local_file_content;
+ Vector<WebView::DocumentStateLocalFileRoot> local_file_roots_of_document_states;
+ HashTable<Web::HTML::CrossProcessId> seen_document_states_with_local_file_roots;
};
}
@@ -1362,11 +1386,11 @@ static ErrorOr<Vector<Web::HTML::SessionHistoryEntryDescriptor>> load_history_en
entries.ensure_capacity(entry_rows.size());
for (auto& row : entry_rows) {
auto container = containers.take(row.entry_ordinal);
- auto held_local_file_content = row.held_local_file_content;
+ auto local_file_root = move(row.local_file_root);
entries.unchecked_append(TRY(build_entry(move(row), move(container))));
auto document_state_id = entries.last().document_state.id;
- if (held_local_file_content && state.seen_document_states_holding_local_file_content.set(document_state_id) == HashSetResult::InsertedNewEntry)
- state.document_states_holding_local_file_content.append(document_state_id);
+ if (local_file_root.has_value() && state.seen_document_states_with_local_file_roots.set(document_state_id) == HashSetResult::InsertedNewEntry)
+ state.local_file_roots_of_document_states.append({ document_state_id, local_file_root.release_value() });
}
if (!containers.is_empty())
return Error::from_string_literal("Session history policy container references a missing entry");
@@ -1470,7 +1494,13 @@ ErrorOr<WebView::SessionHistorySnapshot> load_session_history_snapshot(Database:
row.ever_populated = TRY(result_row.read_bool("ever_populated"sv));
row.reload_pending = TRY(result_row.read_bool("reload_pending"sv));
row.user_agent_initiated = TRY(result_row.read_bool("user_agent_initiated"sv));
- row.held_local_file_content = TRY(result_row.read_bool("held_local_file_content"sv));
+ auto local_file_root_path = TRY(read_optional_snapshot_text(result_row, "local_file_root_path"sv, totals));
+ auto local_file_root_scope = TRY(result_row.read_optional_integer<u8>("local_file_root_scope"sv));
+ if (local_file_root_path.has_value() && local_file_root_scope.has_value()) {
+ if (*local_file_root_scope > to_underlying(WebView::LocalFileRoot::Scope::File))
+ return Error::from_string_literal("Session history entry has an unknown local file root scope");
+ row.local_file_root = WebView::LocalFileRoot { local_file_root_path->to_byte_string(), static_cast<WebView::LocalFileRoot::Scope>(*local_file_root_scope) };
+ }
return row;
}));
@@ -1528,7 +1558,7 @@ ErrorOr<WebView::SessionHistorySnapshot> load_session_history_snapshot(Database:
return Error::from_string_literal("Session history snapshot lacks a unique root history");
snapshot.entries = TRY(load_history_entry_tree(state, *root_history_id, 0));
- snapshot.document_states_holding_local_file_content = move(state.document_states_holding_local_file_content);
+ snapshot.local_file_roots_of_document_states = move(state.local_file_roots_of_document_states);
if (!state.unvisited_histories.is_empty())
return Error::from_string_literal("Session history has an unreachable nested history");
}
diff --git a/UI/Qt/SessionStore.cpp b/UI/Qt/SessionStore.cpp
index 76099112b3f..5a4bf04b3b0 100644
--- a/UI/Qt/SessionStore.cpp
+++ b/UI/Qt/SessionStore.cpp
@@ -29,6 +29,7 @@ static constexpr u32 SESSIONS_SCHEMA_WINDOW_GEOMETRY_VERSION = 8u;
static constexpr u32 SESSIONS_SCHEMA_UPGRADE_INSECURE_REQUESTS_VERSION = 9u;
static constexpr u32 SESSIONS_SCHEMA_RESTART_VERSION = 10u;
static constexpr u32 SESSIONS_SCHEMA_LOCAL_FILE_CONTENT_VERSION = 11u;
+static constexpr u32 SESSIONS_SCHEMA_LOCAL_FILE_ROOTS_VERSION = 12u;
// After this many unclean exits in a row, launch restore stops, so a session that crashes the browser doesn't restore
// into the same crash every time.
@@ -305,6 +306,14 @@ ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_sche
ALTER TABLE SessionEntries ADD COLUMN held_local_file_content INTEGER NOT NULL DEFAULT 0;
)#"sv,
},
+ {
+ .version = SESSIONS_SCHEMA_LOCAL_FILE_ROOTS_VERSION,
+ .sql = R"#(
+ ALTER TABLE SessionEntries DROP COLUMN held_local_file_content;
+ ALTER TABLE SessionEntries ADD COLUMN local_file_root_path TEXT;
+ ALTER TABLE SessionEntries ADD COLUMN local_file_root_scope INTEGER;
+ )#"sv,
+ },
});
return database.migrate("Sessions"sv, migrations, mode);
@@ -1542,9 +1551,9 @@ static bool snapshots_match(Optional<WebView::SessionHistorySnapshot> const& a,
return true;
if (a->current_used_step_index != b->current_used_step_index || a->used_steps != b->used_steps)
return false;
- auto const& a_held = a->document_states_holding_local_file_content;
- auto const& b_held = b->document_states_holding_local_file_content;
- if (a_held.size() != b_held.size() || !all_of(a_held, [&](auto id) { return b_held.contains_slow(id); }))
+ auto const& a_roots = a->local_file_roots_of_document_states;
+ auto const& b_roots = b->local_file_roots_of_document_states;
+ if (a_roots.size() != b_roots.size() || !all_of(a_roots, [&](auto const& root) { return b_roots.contains_slow(root); }))
return false;
return session_history_entry_descriptors_match(a->entries, b->entries);
}