blob: d95646726d63e78e29114fb093589eb8fe27dc5b [file] [log] [blame]
Avi Drissman8ba1bad2022-09-13 19:22:361// Copyright 2012 The Chromium Authors
[email protected]4360ae72012-10-09 22:10:462// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]62885ab2013-01-23 03:55:165#include "components/navigation_interception/intercept_navigation_delegate.h"
[email protected]4360ae72012-10-09 22:10:466
Gyuyoung Kimcb7965e2018-01-25 00:39:017#include <memory>
8
[email protected]4360ae72012-10-09 22:10:469#include "base/android/jni_android.h"
10#include "base/android/jni_string.h"
Avi Drissman12be0312023-01-11 09:16:0911#include "base/functional/bind.h"
12#include "base/functional/callback.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3913#include "base/strings/escape.h"
[email protected]4360ae72012-10-09 22:10:4614#include "content/public/browser/browser_thread.h"
David Bokan2a48f7bb2021-07-09 13:21:3615#include "content/public/browser/navigation_handle.h"
clamy40c9e142015-09-29 11:18:4716#include "content/public/browser/navigation_throttle.h"
jaekyun038903192015-03-31 14:15:5917#include "content/public/browser/render_frame_host.h"
[email protected]4360ae72012-10-09 22:10:4618#include "content/public/browser/render_view_host.h"
19#include "content/public/browser/web_contents.h"
Michael Thiessen41821c982023-08-14 21:45:5420#include "content/public/common/page_visibility_state.h"
Michael Thiessen1a49e4d52022-12-02 21:54:4021#include "mojo/public/cpp/bindings/self_owned_receiver.h"
22#include "net/http/http_status_code.h"
23#include "net/http/http_util.h"
24#include "net/url_request/redirect_info.h"
25#include "net/url_request/redirect_util.h"
26#include "services/network/public/cpp/parsed_headers.h"
27#include "services/network/public/cpp/resource_request.h"
28#include "services/network/public/cpp/single_request_url_loader_factory.h"
29#include "services/network/public/mojom/url_response_head.mojom.h"
Michael Thiessenca245a382022-02-21 16:11:1730#include "url/android/gurl_android.h"
[email protected]e3b599e2013-07-05 07:15:1731#include "url/gurl.h"
[email protected]4360ae72012-10-09 22:10:4632
Andrew Grieveecb885bb2024-05-29 18:14:1933// Must come after all headers that specialize FromJniType() / ToJniType().
34#include "components/navigation_interception/jni_headers/InterceptNavigationDelegate_jni.h"
35
[email protected]4360ae72012-10-09 22:10:4636using base::android::ConvertUTF8ToJavaString;
37using base::android::ScopedJavaLocalRef;
38using content::BrowserThread;
39using content::RenderViewHost;
40using content::WebContents;
Michael Thiessenca245a382022-02-21 16:11:1741using ui::PageTransition;
[email protected]4360ae72012-10-09 22:10:4642
[email protected]8812e3d02013-05-22 12:38:5343namespace navigation_interception {
[email protected]4360ae72012-10-09 22:10:4644
45namespace {
46
thestig3b6a2f12015-09-25 08:17:2047const void* const kInterceptNavigationDelegateUserDataKey =
[email protected]4360ae72012-10-09 22:10:4648 &kInterceptNavigationDelegateUserDataKey;
49
Michael Thiessen8c2b10e2025-01-23 17:54:1950void AllowNavigationToProceed(
51 content::NavigationHandle* navigation_handle,
52 bool should_run_async,
53 InterceptNavigationThrottle::ResultCallback result_callback) {
54 std::move(result_callback).Run(false);
[email protected]4360ae72012-10-09 22:10:4655}
56
Michael Thiessen1a49e4d52022-12-02 21:54:4057class RedirectURLLoader : public network::mojom::URLLoader {
58 public:
Michael Thiessen7b531172023-01-28 05:25:5959 RedirectURLLoader(const network::ResourceRequest& resource_request,
Michael Thiessen1a49e4d52022-12-02 21:54:4060 mojo::PendingRemote<network::mojom::URLLoaderClient> client)
Michael Thiessen7b531172023-01-28 05:25:5961 : client_(std::move(client)), request_(resource_request) {}
62
63 void DoRedirect(std::unique_ptr<GURL> url) {
Michael Thiessen1a49e4d52022-12-02 21:54:4064 net::HttpStatusCode response_code = net::HTTP_TEMPORARY_REDIRECT;
65 auto response_head = network::mojom::URLResponseHead::New();
66 response_head->encoded_data_length = 0;
67 response_head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(
68 net::HttpUtil::AssembleRawHeaders("HTTP/1.1 307 Temporary Redirect"));
69
70 // Avoid a round-trip to the network service by pre-parsing headers.
71 // This doesn't violate: `docs/security/rule-of-2.md`, because the input is
72 // trusted, before appending the Location: <url> header.
73 response_head->parsed_headers =
Michael Thiessen7b531172023-01-28 05:25:5974 network::PopulateParsedHeaders(response_head->headers.get(), *url);
Michael Thiessen1a49e4d52022-12-02 21:54:4075
Michael Thiessen7b531172023-01-28 05:25:5976 response_head->headers->AddHeader("Location", url->spec());
Michael Thiessen1a49e4d52022-12-02 21:54:4077
78 auto first_party_url_policy =
Michael Thiessen7b531172023-01-28 05:25:5979 request_.update_first_party_url_on_redirect
Michael Thiessen1a49e4d52022-12-02 21:54:4080 ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT
81 : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL;
82
83 client_->OnReceiveRedirect(
84 net::RedirectInfo::ComputeRedirectInfo(
Michael Thiessen7b531172023-01-28 05:25:5985 request_.method, request_.url, request_.site_for_cookies,
86 first_party_url_policy, request_.referrer_policy,
Arthur Sonzognic571efb2024-01-26 20:26:1887 request_.referrer.spec(), response_code, *url, std::nullopt,
Michael Thiessen1a49e4d52022-12-02 21:54:4088 /*insecure_scheme_was_upgraded=*/false,
89 /*copy_fragment=*/false),
90 std::move(response_head));
91 }
92
Michael Thiessen7b531172023-01-28 05:25:5993 void OnNonRedirectAsyncAction() {
94 client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_ABORTED));
95 }
96
Michael Thiessen1a49e4d52022-12-02 21:54:4097 RedirectURLLoader(const RedirectURLLoader&) = delete;
98 RedirectURLLoader& operator=(const RedirectURLLoader&) = delete;
99
100 ~RedirectURLLoader() override = default;
101
102 private:
103 // network::mojom::URLLoader overrides:
104 void FollowRedirect(
105 const std::vector<std::string>& removed_headers,
106 const net::HttpRequestHeaders& modified_headers,
107 const net::HttpRequestHeaders& modified_cors_exempt_headers,
Arthur Sonzognic571efb2024-01-26 20:26:18108 const std::optional<GURL>& new_url) override {
Peter Boström77d21352024-11-13 22:26:11109 NOTREACHED();
Michael Thiessen1a49e4d52022-12-02 21:54:40110 }
111 void SetPriority(net::RequestPriority priority,
112 int intra_priority_value) override {}
Michael Thiessen1a49e4d52022-12-02 21:54:40113
114 mojo::Remote<network::mojom::URLLoaderClient> client_;
Michael Thiessen7b531172023-01-28 05:25:59115 network::ResourceRequest request_;
Michael Thiessen1a49e4d52022-12-02 21:54:40116};
117
[email protected]a8e69a742013-10-15 10:58:55118} // namespace
[email protected]4360ae72012-10-09 22:10:46119
120// static
121void InterceptNavigationDelegate::Associate(
122 WebContents* web_contents,
dcheng84c358e2016-04-26 07:05:53123 std::unique_ptr<InterceptNavigationDelegate> delegate) {
Michael Thiessen8595d4742025-03-11 17:06:55124 if (!delegate) {
125 web_contents->RemoveUserData(kInterceptNavigationDelegateUserDataKey);
126 } else {
127 web_contents->SetUserData(kInterceptNavigationDelegateUserDataKey,
128 std::move(delegate));
129 }
[email protected]4360ae72012-10-09 22:10:46130}
131
132// static
133InterceptNavigationDelegate* InterceptNavigationDelegate::Get(
134 WebContents* web_contents) {
dtrainor037df0d2014-10-08 18:05:24135 return static_cast<InterceptNavigationDelegate*>(
[email protected]4360ae72012-10-09 22:10:46136 web_contents->GetUserData(kInterceptNavigationDelegateUserDataKey));
137}
138
139// static
dcheng84c358e2016-04-26 07:05:53140std::unique_ptr<content::NavigationThrottle>
David Bokan2a48f7bb2021-07-09 13:21:36141InterceptNavigationDelegate::MaybeCreateThrottleFor(
Charlie Harrison3286ab72019-02-13 20:13:30142 content::NavigationHandle* handle,
143 navigation_interception::SynchronyMode mode) {
David Bokan2a48f7bb2021-07-09 13:21:36144 // Navigations in a subframe or non-primary frame tree should not be
145 // intercepted. As examples of a non-primary frame tree, a navigation
146 // occurring in a Portal element or an unactivated prerendering page should
147 // not launch an app.
148 // TODO(bokan): This is a bit of a stopgap approach since we won't run
149 // throttles again when the prerender is activated which means links that are
150 // prerendered will avoid launching an app intent that a regular navigation
151 // would have. Longer term we'll want prerender activation to check for app
152 // intents, or have this throttle cancel the prerender if an intent would
153 // have been launched (without launching the intent). It's also not clear
154 // what the right behavior for <portal> elements is.
155 // https://crbug.com/1227659.
156 if (!handle->IsInPrimaryMainFrame())
157 return nullptr;
158
Michael Thiessen8c2b10e2025-01-23 17:54:19159 InterceptNavigationDelegate* intercept_navigation_delegate =
160 InterceptNavigationDelegate::Get(handle->GetWebContents());
161
162 if (!intercept_navigation_delegate) {
163 return std::make_unique<InterceptNavigationThrottle>(
164 handle, base::BindRepeating(&AllowNavigationToProceed), mode,
165 base::DoNothing());
166 }
167
Gyuyoung Kimcb7965e2018-01-25 00:39:01168 return std::make_unique<InterceptNavigationThrottle>(
Michael Thiessen8c2b10e2025-01-23 17:54:19169 handle,
170 base::BindRepeating(&InterceptNavigationDelegate::ShouldIgnoreNavigation,
171 base::Unretained(intercept_navigation_delegate)),
172 mode,
173 base::BindRepeating(
Michael Thiessen729a4672025-01-29 20:38:35174 &InterceptNavigationDelegate::RequestFinishPendingShouldIgnoreCheck,
Michael Thiessen8c2b10e2025-01-23 17:54:19175 base::Unretained(intercept_navigation_delegate)));
[email protected]4360ae72012-10-09 22:10:46176}
177
178InterceptNavigationDelegate::InterceptNavigationDelegate(
Colin Blundell4695e8142020-03-16 11:13:12179 JNIEnv* env,
Andrew Grievedf3420a4e2024-08-30 21:02:48180 const jni_zero::JavaRef<jobject>& jdelegate,
Colin Blundell4695e8142020-03-16 11:13:12181 bool escape_external_handler_value)
182 : weak_jdelegate_(env, jdelegate),
183 escape_external_handler_value_(escape_external_handler_value) {}
[email protected]4360ae72012-10-09 22:10:46184
Michael Thiessen1a49e4d52022-12-02 21:54:40185InterceptNavigationDelegate::~InterceptNavigationDelegate() = default;
[email protected]4360ae72012-10-09 22:10:46186
Michael Thiessen8c2b10e2025-01-23 17:54:19187void InterceptNavigationDelegate::ShouldIgnoreNavigation(
188 content::NavigationHandle* navigation_handle,
189 bool should_run_async,
190 InterceptNavigationThrottle::ResultCallback result_callback) {
191 DCHECK_CURRENTLY_ON(BrowserThread::UI);
192 // Avoid having two outstanding checks at once for simplicity.
193 if (should_ignore_result_callback_) {
Michael Thiessenec04a4a2025-02-24 16:01:54194 std::move(result_callback).Run(false);
195 return;
Michael Thiessen8c2b10e2025-01-23 17:54:19196 }
Michael Thiessenca245a382022-02-21 16:11:17197 GURL escaped_url = escape_external_handler_value_
Ryan Hamilton7f3bd3d2022-04-23 00:07:39198 ? GURL(base::EscapeExternalHandlerValue(
Michael Thiessenca245a382022-02-21 16:11:17199 navigation_handle->GetURL().spec()))
200 : navigation_handle->GetURL();
Colin Blundell4695e8142020-03-16 11:13:12201
Michael Thiessen8c2b10e2025-01-23 17:54:19202 if (!escaped_url.is_valid()) {
203 std::move(result_callback).Run(false);
204 return;
205 }
[email protected]4360ae72012-10-09 22:10:46206
207 JNIEnv* env = base::android::AttachCurrentThread();
208 ScopedJavaLocalRef<jobject> jdelegate = weak_jdelegate_.get(env);
209
Michael Thiessen8c2b10e2025-01-23 17:54:19210 if (jdelegate.is_null()) {
211 std::move(result_callback).Run(false);
212 return;
213 }
[email protected]4360ae72012-10-09 22:10:46214
Michael Thiessen41821c982023-08-14 21:45:54215 bool hidden_cross_frame = false;
Michael Thiessen884e6172023-02-13 17:50:31216 // Only main frame navigations use this path, so we only need to check if the
217 // navigation is cross-frame to the main frame.
Michael Thiessen41821c982023-08-14 21:45:54218 if (navigation_handle->GetInitiatorFrameToken() &&
219 navigation_handle->GetInitiatorFrameToken() !=
220 navigation_handle->GetWebContents()
221 ->GetPrimaryMainFrame()
222 ->GetFrameToken()) {
223 content::RenderFrameHost* initiator_frame_host =
224 content::RenderFrameHost::FromFrameToken(
Dave Tapuskae9b7c0f72023-11-06 16:38:01225 content::GlobalRenderFrameHostToken(
226 navigation_handle->GetInitiatorProcessId(),
227 navigation_handle->GetInitiatorFrameToken().value()));
Michael Thiessen41821c982023-08-14 21:45:54228 // If the initiator is gone treat it as not visible.
229 hidden_cross_frame =
230 !initiator_frame_host || initiator_frame_host->GetVisibilityState() !=
231 content::PageVisibilityState::kVisible;
232 }
Michael Thiessen884e6172023-02-13 17:50:31233
Michael Thiessen8fd3520b2023-03-10 20:55:47234 // We don't care which sandbox flags are present, only that any sandbox flags
235 // are present, as we don't support persisting sandbox flags through fallback
236 // URL navigation.
237 bool is_sandboxed = navigation_handle->SandboxFlagsInherited() !=
Michael Thiessend80a1af12023-08-21 17:17:35238 network::mojom::WebSandboxFlags::kNone ||
239 navigation_handle->SandboxFlagsInitiator() !=
240 network::mojom::WebSandboxFlags::kNone;
Arthur Sonzognidc8508ab2023-08-17 08:42:42241
Michael Thiessen8c2b10e2025-01-23 17:54:19242 should_ignore_result_callback_ = std::move(result_callback);
243 Java_InterceptNavigationDelegate_callShouldIgnoreNavigation(
Michael Thiessenca245a382022-02-21 16:11:17244 env, jdelegate, navigation_handle->GetJavaNavigationHandle(),
Michael Thiessen41821c982023-08-14 21:45:54245 url::GURLAndroid::FromNativeGURL(env, escaped_url), hidden_cross_frame,
Michael Thiessen8c2b10e2025-01-23 17:54:19246 is_sandboxed, should_run_async);
247}
248
249void InterceptNavigationDelegate::OnShouldIgnoreNavigationResult(
250 bool should_ignore) {
251 std::move(should_ignore_result_callback_).Run(should_ignore);
252}
253
Michael Thiessen729a4672025-01-29 20:38:35254void InterceptNavigationDelegate::RequestFinishPendingShouldIgnoreCheck() {
Michael Thiessen8c2b10e2025-01-23 17:54:19255 JNIEnv* env = base::android::AttachCurrentThread();
256 ScopedJavaLocalRef<jobject> jdelegate = weak_jdelegate_.get(env);
257
258 if (jdelegate.is_null()) {
259 OnShouldIgnoreNavigationResult(false);
260 return;
261 }
Michael Thiessen729a4672025-01-29 20:38:35262 Java_InterceptNavigationDelegate_requestFinishPendingShouldIgnoreCheck(
263 env, jdelegate);
Michael Thiessenca245a382022-02-21 16:11:17264}
265
Michael Thiessen7cb129e2022-11-08 17:24:51266void InterceptNavigationDelegate::HandleSubframeExternalProtocol(
Michael Thiessenca245a382022-02-21 16:11:17267 const GURL& url,
268 ui::PageTransition page_transition,
269 bool has_user_gesture,
Arthur Sonzognic571efb2024-01-26 20:26:18270 const std::optional<url::Origin>& initiating_origin,
Michael Thiessen1a49e4d52022-12-02 21:54:40271 mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) {
Michael Thiessen7b531172023-01-28 05:25:59272 // If there's a pending async subframe action, don't consider external
273 // navigation for the current navigation.
274 if (subframe_redirect_url_ || url_loader_) {
275 return;
276 }
277
Michael Thiessenca245a382022-02-21 16:11:17278 GURL escaped_url = escape_external_handler_value_
Ryan Hamilton7f3bd3d2022-04-23 00:07:39279 ? GURL(base::EscapeExternalHandlerValue(url.spec()))
Michael Thiessenca245a382022-02-21 16:11:17280 : url;
281 if (!escaped_url.is_valid())
282 return;
283
284 JNIEnv* env = base::android::AttachCurrentThread();
285 ScopedJavaLocalRef<jobject> jdelegate = weak_jdelegate_.get(env);
286
287 if (jdelegate.is_null())
288 return;
Michael Thiessen1a49e4d52022-12-02 21:54:40289 ScopedJavaLocalRef<jobject> j_gurl =
290 Java_InterceptNavigationDelegate_handleSubframeExternalProtocol(
291 env, jdelegate, url::GURLAndroid::FromNativeGURL(env, escaped_url),
292 page_transition, has_user_gesture,
Andrew Grieve6a37bcd2024-09-26 21:47:44293 initiating_origin ? initiating_origin->ToJavaObject(env) : nullptr);
Michael Thiessen1a49e4d52022-12-02 21:54:40294 if (j_gurl.is_null())
295 return;
Andrew Grieve7912fd32024-04-15 17:23:05296 subframe_redirect_url_ =
297 std::make_unique<GURL>(url::GURLAndroid::ToNativeGURL(env, j_gurl));
Michael Thiessen1a49e4d52022-12-02 21:54:40298
299 mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver =
300 out_factory->InitWithNewPipeAndPassReceiver();
301 scoped_refptr<network::SharedURLLoaderFactory> loader_factory =
302 base::MakeRefCounted<network::SingleRequestURLLoaderFactory>(
Michael Thiessen7b531172023-01-28 05:25:59303 base::BindOnce(&InterceptNavigationDelegate::LoaderCallback,
304 weak_ptr_factory_.GetWeakPtr()));
Michael Thiessen1a49e4d52022-12-02 21:54:40305 loader_factory->Clone(std::move(receiver));
[email protected]4360ae72012-10-09 22:10:46306}
307
Michael Thiessen7b531172023-01-28 05:25:59308void InterceptNavigationDelegate::LoaderCallback(
309 const network::ResourceRequest& resource_request,
310 mojo::PendingReceiver<network::mojom::URLLoader> pending_receiver,
311 mojo::PendingRemote<network::mojom::URLLoaderClient> pending_client) {
312 url_loader_ = mojo::MakeSelfOwnedReceiver(
313 std::make_unique<RedirectURLLoader>(resource_request,
314 std::move(pending_client)),
315 std::move(pending_receiver));
316 MaybeHandleSubframeAction();
317}
318
319void InterceptNavigationDelegate::MaybeHandleSubframeAction() {
320 // An empty subframe_redirect_url_ implies a pending async action.
321 if (!url_loader_ ||
322 (subframe_redirect_url_ && subframe_redirect_url_->is_empty())) {
323 return;
324 }
325 RedirectURLLoader* loader =
326 static_cast<RedirectURLLoader*>(url_loader_->impl());
327 if (!subframe_redirect_url_) {
328 loader->OnNonRedirectAsyncAction();
329 } else {
330 loader->DoRedirect(std::move(subframe_redirect_url_));
331 }
332 url_loader_.reset();
333}
334
Michael Thiessen332dadb62022-07-13 14:44:07335void InterceptNavigationDelegate::OnResourceRequestWithGesture() {
336 JNIEnv* env = base::android::AttachCurrentThread();
337 ScopedJavaLocalRef<jobject> jdelegate = weak_jdelegate_.get(env);
338 if (jdelegate.is_null())
339 return;
340 Java_InterceptNavigationDelegate_onResourceRequestWithGesture(env, jdelegate);
Michael Thiessene5663522022-05-25 21:23:28341}
342
Michael Thiessen7b531172023-01-28 05:25:59343void InterceptNavigationDelegate::OnSubframeAsyncActionTaken(
344 JNIEnv* env,
345 const base::android::JavaParamRef<jobject>& j_gurl) {
346 // subframe_redirect_url_ no longer empty indicates the async action has been
347 // taken.
348 subframe_redirect_url_ =
Andrew Grieve7912fd32024-04-15 17:23:05349 j_gurl.is_null()
350 ? nullptr
351 : std::make_unique<GURL>(url::GURLAndroid::ToNativeGURL(env, j_gurl));
Michael Thiessen7b531172023-01-28 05:25:59352 MaybeHandleSubframeAction();
353}
354
Michael Thiessen8c2b10e2025-01-23 17:54:19355static void JNI_InterceptNavigationDelegate_OnShouldIgnoreNavigationResult(
356 JNIEnv* env,
357 const base::android::JavaParamRef<jobject>& jweb_contents,
358 jboolean should_ignore) {
359 content::WebContents* web_contents =
360 content::WebContents::FromJavaWebContents(jweb_contents);
361 if (!web_contents) {