blob: 3b7c2c3df51d46f96f00f5e568ce2e5f90617b6b [file] [log] [blame]
danakjc492bf82020-09-09 20:02:441// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CONTENT_BROWSER_RENDERER_HOST_FRAME_TREE_NODE_H_
6#define CONTENT_BROWSER_RENDERER_HOST_FRAME_TREE_NODE_H_
7
8#include <stddef.h>
9
10#include <memory>
11#include <string>
12#include <vector>
13
14#include "base/gtest_prod_util.h"
15#include "base/macros.h"
16#include "base/memory/ref_counted.h"
17#include "content/browser/renderer_host/frame_tree.h"
18#include "content/browser/renderer_host/frame_tree_node_blame_context.h"
19#include "content/browser/renderer_host/navigator.h"
20#include "content/browser/renderer_host/render_frame_host_impl.h"
21#include "content/browser/renderer_host/render_frame_host_manager.h"
22#include "content/common/content_export.h"
23#include "content/common/frame_replication_state.h"
24#include "services/network/public/mojom/content_security_policy.mojom-forward.h"
25#include "third_party/blink/public/common/frame/frame_policy.h"
26#include "third_party/blink/public/common/frame/user_activation_state.h"
27#include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom.h"
28#include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h"
29#include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom.h"
30#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom-forward.h"
31
32#include "url/gurl.h"
33#include "url/origin.h"
34
35namespace content {
36
37class NavigationRequest;
38class RenderFrameHostImpl;
39class NavigationEntryImpl;
40
41// When a page contains iframes, its renderer process maintains a tree structure
42// of those frames. We are mirroring this tree in the browser process. This
43// class represents a node in this tree and is a wrapper for all objects that
44// are frame-specific (as opposed to page-specific).
45//
46// Each FrameTreeNode has a current RenderFrameHost, which can change over
47// time as the frame is navigated. Any immediate subframes of the current
48// document are tracked using FrameTreeNodes owned by the current
49// RenderFrameHost, rather than as children of FrameTreeNode itself. This
50// allows subframe FrameTreeNodes to stay alive while a RenderFrameHost is
51// still alive - for example while pending deletion, after a new current
52// RenderFrameHost has replaced it.
53class CONTENT_EXPORT FrameTreeNode {
54 public:
55 class Observer {
56 public:
57 // Invoked when a FrameTreeNode is being destroyed.
58 virtual void OnFrameTreeNodeDestroyed(FrameTreeNode* node) {}
59
60 // Invoked when a FrameTreeNode becomes focused.
61 virtual void OnFrameTreeNodeFocused(FrameTreeNode* node) {}
62
63 virtual ~Observer() {}
64 };
65
66 static const int kFrameTreeNodeInvalidId;
67
68 // Returns the FrameTreeNode with the given global |frame_tree_node_id|,
69 // regardless of which FrameTree it is in.
70 static FrameTreeNode* GloballyFindByID(int frame_tree_node_id);
71
72 // Returns the FrameTreeNode for the given |rfh|. Same as
73 // rfh->frame_tree_node(), but also supports nullptrs.
74 static FrameTreeNode* From(RenderFrameHost* rfh);
75
76 // Callers are are expected to initialize sandbox flags separately after
77 // calling the constructor.
78 FrameTreeNode(
79 FrameTree* frame_tree,
80 RenderFrameHostImpl* parent,
81 blink::mojom::TreeScopeType scope,
82 const std::string& name,
83 const std::string& unique_name,
84 bool is_created_by_script,
85 const base::UnguessableToken& devtools_frame_token,
86 const blink::mojom::FrameOwnerProperties& frame_owner_properties,
87 blink::mojom::FrameOwnerElementType owner_type);
88
89 ~FrameTreeNode();
90
91 void AddObserver(Observer* observer);
92 void RemoveObserver(Observer* observer);
93
94 bool IsMainFrame() const;
95
96 // Clears any state in this node which was set by the document itself (CSP
97 // Headers, Feature Policy Headers, and CSP-set sandbox flags), and notifies
98 // proxies as appropriate. Invoked after committing navigation to a new
99 // document (since the new document comes with a fresh set of CSP and
100 // Feature-Policy HTTP headers).
101 void ResetForNavigation();
102
103 FrameTree* frame_tree() const { return frame_tree_; }
104 Navigator& navigator() { return frame_tree()->navigator(); }
105
106 RenderFrameHostManager* render_manager() { return &render_manager_; }
107 int frame_tree_node_id() const { return frame_tree_node_id_; }
108 const std::string& frame_name() const { return replication_state_.name; }
109
110 const std::string& unique_name() const {
111 return replication_state_.unique_name;
112 }
113
114 // See comment on the member declaration.
115 const base::UnguessableToken& devtools_frame_token() const {
116 return devtools_frame_token_;
117 }
118
119 size_t child_count() const { return current_frame_host()->child_count(); }
120
121 unsigned int depth() const { return depth_; }
122
123 RenderFrameHostImpl* parent() const { return parent_; }
124
125 FrameTreeNode* opener() const { return opener_; }
126
127 FrameTreeNode* original_opener() const { return original_opener_; }
128
Wolfgang Beyerd8809db2020-09-30 15:29:39129 const base::Optional<base::UnguessableToken>& opener_devtools_frame_token() {
130 return opener_devtools_frame_token_;
131 }
132
danakjc492bf82020-09-09 20:02:44133 // Gets the total number of descendants to this FrameTreeNode in addition to
134 // this node.
135 size_t GetFrameTreeSize() const;
136
137 // Assigns a new opener for this node and, if |opener| is non-null, registers
138 // an observer that will clear this node's opener if |opener| is ever
139 // destroyed.
140 void SetOpener(FrameTreeNode* opener);
141
142 // Assigns the initial opener for this node, and if |opener| is non-null,
143 // registers an observer that will clear this node's opener if |opener| is
144 // ever destroyed. The value set here is the root of the tree.
145 //
146 // It is not possible to change the opener once it was set.
147 void SetOriginalOpener(FrameTreeNode* opener);
148
Wolfgang Beyerd8809db2020-09-30 15:29:39149 // Assigns an opener frame id for this node. This string id is only set once
150 // and cannot be changed. It persists, even if the |opener| is destroyed. It
151 // is used for attribution in the DevTools frontend.
152 void SetOpenerDevtoolsFrameToken(
153 base::UnguessableToken opener_devtools_frame_token);
154
danakjc492bf82020-09-09 20:02:44155 FrameTreeNode* child_at(size_t index) const {
156 return current_frame_host()->child_at(index);
157 }
158
159 // Returns the URL of the last committed page in the current frame.
160 const GURL& current_url() const {
161 return current_frame_host()->GetLastCommittedURL();
162 }
163
164 // Sets the last committed URL for this frame and updates
165 // has_committed_real_load accordingly.
166 void SetCurrentURL(const GURL& url);
167
168 // Returns true iff SetCurrentURL has been called with a non-blank URL.
169 bool has_committed_real_load() const { return has_committed_real_load_; }
170
171 // Returns whether the frame's owner element in the parent document is
172 // collapsed, that is, removed from the layout as if it did not exist, as per
173 // request by the embedder (of the content/ layer).
174 bool is_collapsed() const { return is_collapsed_; }
175
176 // Sets whether to collapse the frame's owner element in the parent document,
177 // that is, to remove it from the layout as if it did not exist, as per
178 // request by the embedder (of the content/ layer). Cannot be called for main
179 // frames.
180 //
181 // This only has an effect for <iframe> owner elements, and is a no-op when
182 // called on sub-frames hosted in <frame>, <object>, and <embed> elements.
183 void SetCollapsed(bool collapsed);
184
185 // Returns the origin of the last committed page in this frame.
186 // WARNING: To get the last committed origin for a particular
187 // RenderFrameHost, use RenderFrameHost::GetLastCommittedOrigin() instead,
188 // which will behave correctly even when the RenderFrameHost is not the
189 // current one for this frame (such as when it's pending deletion).
190 const url::Origin& current_origin() const {
191 return replication_state_.origin;
192 }
193
194 // Set the current origin and notify proxies about the update.
195 void SetCurrentOrigin(const url::Origin& origin,
196 bool is_potentially_trustworthy_unique_origin);
197
198 // Set the current name and notify proxies about the update.
199 void SetFrameName(const std::string& name, const std::string& unique_name);
200
201 // Add CSP headers to replication state, notify proxies about the update.
202 void AddContentSecurityPolicies(
203 std::vector<network::mojom::ContentSecurityPolicyHeaderPtr> headers);
204
205 // Sets the current insecure request policy, and notifies proxies about the
206 // update.
207 void SetInsecureRequestPolicy(blink::mojom::InsecureRequestPolicy policy);
208
209 // Sets the current set of insecure urls to upgrade, and notifies proxies
210 // about the update.
211 void SetInsecureNavigationsSet(
212 const std::vector<uint32_t>& insecure_navigations_set);
213
214 // Returns the latest frame policy (sandbox flags and container policy) for
215 // this frame. This includes flags inherited from parent frames and the latest
216 // flags from the <iframe> element hosting this frame. The returned policies
217 // may not yet have taken effect, since "sandbox" and "allow" attribute
218 // updates in an <iframe> element take effect on next navigation. To retrieve
219 // the currently active policy for this frame, use effective_frame_policy().
220 const blink::FramePolicy& pending_frame_policy() const {
221 return pending_frame_policy_;
222 }
223
224 // Update this frame's sandbox flags and container policy. This is called
225 // when a parent frame updates the "sandbox" attribute in the <iframe> element
226 // for this frame, or any of the attributes which affect the container policy
227 // ("allowfullscreen", "allowpaymentrequest", "allow", and "src".)
228 // These policies won't take effect until next navigation. If this frame's
229 // parent is itself sandboxed, the parent's sandbox flags are combined with
230 // those in |frame_policy|.
231 // Attempting to change the container policy on the main frame will have no
232 // effect.
233 void SetPendingFramePolicy(blink::FramePolicy frame_policy);
234
235 // Returns the currently active frame policy for this frame, including the
236 // sandbox flags which were present at the time the document was loaded, and
237 // the feature policy container policy, which is set by the iframe's
238 // allowfullscreen, allowpaymentrequest, and allow attributes, along with the
239 // origin of the iframe's src attribute (which may be different from the URL
240 // of the document currently loaded into the frame). This does not include
241 // policy changes that have been made by updating the containing iframe
242 // element attributes since the frame was last navigated; use
243 // pending_frame_policy() for those.
244 const blink::FramePolicy& effective_frame_policy() const {
245 return replication_state_.frame_policy;
246 }
247
248 // Set the frame_policy provided in function parameter as active frame policy,
249 // while leaving pending_frame_policy_ untouched.
250 bool CommitFramePolicy(const blink::FramePolicy& frame_policy);
251
252 const blink::mojom::FrameOwnerProperties& frame_owner_properties() {
253 return frame_owner_properties_;
254 }
255
256 void set_frame_owner_properties(
257 const blink::mojom::FrameOwnerProperties& frame_owner_properties) {
258 frame_owner_properties_ = frame_owner_properties;
259 }
260
261 const network::mojom::ContentSecurityPolicy* csp_attribute() {
262 return csp_attribute_.get();
263 }
264
265 void set_csp_attribute(
266 network::mojom::ContentSecurityPolicyPtr parsed_csp_attribute) {
267 csp_attribute_ = std::move(parsed_csp_attribute);
268 }
269
270 bool HasSameOrigin(const FrameTreeNode& node) const {
271 return replication_state_.origin.IsSameOriginWith(
272 node.replication_state_.origin);
273 }
274
275 const FrameReplicationState& current_replication_state() const {
276 return replication_state_;
277 }
278
279 RenderFrameHostImpl* current_frame_host() const {
280 return render_manager_.current_frame_host();
281 }
282
283 // Return the node immediately preceding this node in its parent's children,
284 // or nullptr if there is no such node.
285 FrameTreeNode* PreviousSibling() const;
286
287 // Return the node immediately following this node in its parent's children,
288 // or nullptr if there is no such node.
289 FrameTreeNode* NextSibling() const;
290
291 // Returns true if this node is in a loading state.
292 bool IsLoading() const;
293
294 NavigationRequest* navigation_request() { return navigation_request_.get(); }
295
296 // Transfers the ownership of the NavigationRequest to |render_frame_host|.
297 // From ReadyToCommit to DidCommit, the NavigationRequest is owned by the
298 // RenderFrameHost that is committing the navigation.
299 void TransferNavigationRequestOwnership(
300 RenderFrameHostImpl* render_frame_host);
301
302 // Takes ownership of |navigation_request| and makes it the current
303 // NavigationRequest of this frame. This corresponds to the start of a new
304 // navigation. If there was an ongoing navigation request before calling this
305 // function, it is canceled. |navigation_request| should not be null.
306 void CreatedNavigationRequest(
307 std::unique_ptr<NavigationRequest> navigation_request);
308
309 // Resets the current navigation request. If |keep_state| is true, any state
310 // created by the NavigationRequest (e.g. speculative RenderFrameHost,
311 // loading state) will not be reset by the function.
312 void ResetNavigationRequest(bool keep_state);
313
314 // A RenderFrameHost in this node started loading.
315 // |to_different_document| will be true unless the load is a fragment
316 // navigation, or triggered by history.pushState/replaceState.
317 // |was_previously_loading| is false if the FrameTree was not loading before.
318 // The caller is required to provide this boolean as the delegate should only
319 // be notified if the FrameTree went from non-loading to loading state.
320 // However, when it is called, the FrameTree should be in a loading state.
321 void DidStartLoading(bool to_different_document, bool was_previously_loading);
322
323 // A RenderFrameHost in this node stopped loading.
324 void DidStopLoading();
325
326 // The load progress for a RenderFrameHost in this node was updated to
327 // |load_progress|. This will notify the FrameTree which will in turn notify
328 // the WebContents.
329 void DidChangeLoadProgress(double load_progress);
330
331 // Called when the user directed the page to stop loading. Stops all loads
332 // happening in the FrameTreeNode. This method should be used with
333 // FrameTree::ForEach to stop all loads in the entire FrameTree.
334 bool StopLoading();
335
336 // Returns the time this frame was last focused.
337 base::TimeTicks last_focus_time() const { return last_focus_time_; }
338
339 // Called when this node becomes focused. Updates the node's last focused
340 // time and notifies observers.
341 void DidFocus();
342
343 // Called when the user closed the modal dialogue for BeforeUnload and
344 // cancelled the navigation. This should stop any load happening in the
345 // FrameTreeNode.
346 void BeforeUnloadCanceled();
347
348 // Returns the BlameContext associated with this node.
349 FrameTreeNodeBlameContext& blame_context() { return blame_context_; }
350
351 // Updates the user activation state in the browser frame tree and in the
352 // frame trees in all renderer processes except the renderer for this node
353 // (which initiated the update). Returns |false| if the update tries to
354 // consume an already consumed/expired transient state, |true| otherwise. See
355 // the comment on user_activation_state_ below.
356 //
357 // The |notification_type| parameter is used for histograms, only for the case
358 // |update_state == kNotifyActivation|.
359 bool UpdateUserActivationState(
360 blink::mojom::UserActivationUpdateType update_type,
361 blink::mojom::UserActivationNotificationType notification_type);
362
363 void OnSetHadStickyUserActivationBeforeNavigation(bool value);
364
365 // Returns the sandbox flags currently in effect for this frame. This includes
366 // flags inherited from parent frames, the currently active flags from the
367 // <iframe> element hosting this frame, as well as any flags set from a
368 // Content-Security-Policy HTTP header. This does not include flags that have
369 // have been updated in an <iframe> element but have not taken effect yet; use
370 // pending_frame_policy() for those. To see the flags which will take effect
371 // on navigation (which does not include the CSP-set flags), use
372 // effective_frame_policy().
373 network::mojom::WebSandboxFlags active_sandbox_flags() const {
374 return replication_state_.active_sandbox_flags;
375 }
376
377 // Updates the active sandbox flags in this frame, in response to a
378 // Content-Security-Policy header adding additional flags, in addition to
379 // those given to this frame by its parent, or in response to the
380 // Feature-Policy header being set. Note that on navigation, these updates
381 // will be cleared, and the flags in the pending frame policy will be applied
382 // to the frame.
383 void UpdateFramePolicyHeaders(
384 network::mojom::WebSandboxFlags sandbox_flags,
385 const blink::ParsedFeaturePolicy& parsed_header);
386
387 // Returns whether the frame received a user gesture on a previous navigation
388 // on the same eTLD+1.
389 bool has_received_user_gesture_before_nav() const {
390 return replication_state_.has_received_user_gesture_before_nav;
391 }
392
393 // When a tab is discarded, WebContents sets was_discarded on its
394 // root FrameTreeNode.
395 // In addition, when a child frame is created, this bit is passed on from
396 // parent to child.
397 // When a navigation request is created, was_discarded is passed on to the
398 // request and reset to false in FrameTreeNode.
399 void set_was_discarded() { was_discarded_ = true; }
400 bool was_discarded() const { return was_discarded_; }
401
402 // Returns the sticky bit of the User Activation v2 state of the
403 // |FrameTreeNode|.
404 bool HasStickyUserActivation() const {
405 return user_activation_state_.HasBeenActive();
406 }
407
408 // Returns the transient bit of the User Activation v2 state of the
409 // |FrameTreeNode|.
410 bool HasTransientUserActivation() {
411 return user_activation_state_.IsActive();
412 }
413
414 // Remove history entries for all frames created by script in this frame's
415 // subtree. If a frame created by a script is removed, then its history entry
416 // will never be reused - this saves memory.
417 void PruneChildFrameNavigationEntries(NavigationEntryImpl* entry);
418
419 blink::mojom::FrameOwnerElementType frame_owner_element_type() const {
420 return replication_state_.frame_owner_element_type;
421 }
422 // Only meaningful to call on a root frame. The value of |feature_state| will
423 // be nontrivial if there is an opener which is restricted in some of the
424 // feature policies.
425 void SetOpenerFeaturePolicyState(
426 const blink::FeaturePolicyFeatureState& feature_state);
427
428 void SetAdFrameType(blink::mojom::AdFrameType ad_frame_type);
429
430 private:
431 FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest,
432 ContainerPolicyDynamic);
433 FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest,
434 ContainerPolicySandboxDynamic);
435
436 class OpenerDestroyedObserver;
437
438 FrameTreeNode* GetSibling(int relative_offset) const;
439
440 // The |notification_type| parameter is used for histograms only.
441 bool NotifyUserActivation(
442 blink::mojom::UserActivationNotificationType notification_type);
443
444 bool ConsumeTransientUserActivation();
445
446 bool ClearUserActivation();
447
448 // Verify that the renderer process is allowed to set user activation on this
449 // frame by checking whether this frame's RenderWidgetHost had previously seen
450 // an input event that might lead to user activation. If user activation
451 // should be allowed, this returns true and also clears corresponding pending
452 // user activation state in the widget. Otherwise, this returns false.
453 bool VerifyUserActivation();
454
455 // The next available browser-global FrameTreeNode ID.
456 static int next_frame_tree_node_id_;
457
458 // The FrameTree that owns us.
459 FrameTree* frame_tree_; // not owned.
460
461 // Manages creation and swapping of RenderFrameHosts for this frame.
462 RenderFrameHostManager render_manager_;
463
464 // A browser-global identifier for the frame in the page, which stays stable
465 // even if the frame does a cross-process navigation.
466 const int frame_tree_node_id_;
467
468 // The RenderFrameHost owning this FrameTreeNode, which cannot change for the
469 // life of this FrameTreeNode. |nullptr| if this node is the root.
470 RenderFrameHostImpl* const parent_;
471
472 // Number of edges from this node to the root. 0 if this is the root.
473 const unsigned int depth_;
474
475 // The frame that opened this frame, if any. Will be set to null if the
476 // opener is closed, or if this frame disowns its opener by setting its
477 // window.opener to null.
478 FrameTreeNode* opener_;
479
480 // An observer that clears this node's |opener_| if the opener is destroyed.
481 // This observer is added to the |opener_|'s observer list when the |opener_|
482 // is set to a non-null node, and it is removed from that list when |opener_|
483 // changes or when this node is destroyed. It is also cleared if |opener_|
484 // is disowned.
485 std::unique_ptr<OpenerDestroyedObserver> opener_observer_;
486
487 // The frame that opened this frame, if any. Contrary to opener_, this
488 // cannot be changed unless the original opener is destroyed.
489 FrameTreeNode* original_opener_;
490
Wolfgang Beyerd8809db2020-09-30 15:29:39491 // The devtools frame token of the frame which opened this frame. This is
492 // not cleared even if the opener is destroyed or disowns the frame.
493 base::Optional<base::UnguessableToken> opener_devtools_frame_token_;
494
danakjc492bf82020-09-09 20:02:44495 // An observer that clears this node's |original_opener_| if the opener is
496 // destroyed.
497 std::unique_ptr<OpenerDestroyedObserver> original_opener_observer_;
498
499 // Whether this frame has committed any real load, replacing its initial
500 // about:blank page.
501 bool has_committed_real_load_;
502
503 // Whether the frame's owner element in the parent document is collapsed.
504 bool is_collapsed_;
505
506 // Track information that needs to be replicated to processes that have
507 // proxies for this frame.
508 FrameReplicationState replication_state_;
509
510 // Track the pending sandbox flags and container policy for this frame. When a
511 // parent frame dynamically updates 'sandbox', 'allow', 'allowfullscreen',
512 // 'allowpaymentrequest' or 'src' attributes, the updated policy for the frame
513 // is stored here, and transferred into replication_state_.frame_policy when
514 // they take effect on the next frame navigation.
515 blink::FramePolicy pending_frame_policy_;
516
517 // Whether the frame was created by javascript. This is useful to prune
518 // history entries when the frame is removed (because frames created by
519 // scripts are never recreated with the same unique name - see
520 // https://crbug.com/500260).
521 bool is_created_by_script_;
522
523 // Used for devtools instrumentation and trace-ability. The token is
524 // propagated to Blink's LocalFrame and both Blink and content/
525 // can tag calls and requests with this token in order to attribute them
526 // to the context frame.
527 // |devtools_frame_token_| is only defined by the browser process and is never
528 // sent back from the renderer in the control calls. It should be never used
529 // to look up the FrameTreeNode instance.
530 base::UnguessableToken devtools_frame_token_;
531
532 // Tracks the scrolling and margin properties for this frame. These
533 // properties affect the child renderer but are stored on its parent's
534 // frame element. When this frame's parent dynamically updates these
535 // properties, we update them here too.
536 //
537 // Note that dynamic updates only take effect on the next frame navigation.
538 blink::mojom::FrameOwnerProperties frame_owner_properties_;
539
540 // Contains the current parsed value of the 'csp' attribute of this frame.
541 network::mojom::ContentSecurityPolicyPtr csp_attribute_;
542
543 // Owns an ongoing NavigationRequest until it is ready to commit. It will then
544 // be reset and a RenderFrameHost will be responsible for the navigation.
545 std::unique_ptr<NavigationRequest> navigation_request_;
546
547 // List of objects observing this FrameTreeNode.
548 base::ObserverList<Observer>::Unchecked observers_;
549
550 base::TimeTicks last_focus_time_;
551
552 bool was_discarded_;
553
554 // The user activation state of the current frame. See |UserActivationState|
555 // for details on how this state is maintained.
556 blink::UserActivationState user_activation_state_;
557
558 // A helper for tracing the snapshots of this FrameTreeNode and attributing
559 // browser process activities to this node (when possible). It is unrelated
560 // to the core logic of FrameTreeNode.
561 FrameTreeNodeBlameContext blame_context_;
562
563 DISALLOW_COPY_AND_ASSIGN(FrameTreeNode);
564};
565
566} // namespace content
567
568#endif // CONTENT_BROWSER_RENDERER_HOST_FRAME_TREE_NODE_H_