blob: dba5bf43f08522eaf2bf274419ae16e6b11c34b4 [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
129 // Gets the total number of descendants to this FrameTreeNode in addition to
130 // this node.
131 size_t GetFrameTreeSize() const;
132
133 // Assigns a new opener for this node and, if |opener| is non-null, registers
134 // an observer that will clear this node's opener if |opener| is ever
135 // destroyed.
136 void SetOpener(FrameTreeNode* opener);
137
138 // Assigns the initial opener for this node, and if |opener| is non-null,
139 // registers an observer that will clear this node's opener if |opener| is
140 // ever destroyed. The value set here is the root of the tree.
141 //
142 // It is not possible to change the opener once it was set.
143 void SetOriginalOpener(FrameTreeNode* opener);
144
145 FrameTreeNode* child_at(size_t index) const {
146 return current_frame_host()->child_at(index);
147 }
148
149 // Returns the URL of the last committed page in the current frame.
150 const GURL& current_url() const {
151 return current_frame_host()->GetLastCommittedURL();
152 }
153
154 // Sets the last committed URL for this frame and updates
155 // has_committed_real_load accordingly.
156 void SetCurrentURL(const GURL& url);
157
158 // Returns true iff SetCurrentURL has been called with a non-blank URL.
159 bool has_committed_real_load() const { return has_committed_real_load_; }
160
161 // Returns whether the frame's owner element in the parent document is
162 // collapsed, that is, removed from the layout as if it did not exist, as per
163 // request by the embedder (of the content/ layer).
164 bool is_collapsed() const { return is_collapsed_; }
165
166 // Sets whether to collapse the frame's owner element in the parent document,
167 // that is, to remove it from the layout as if it did not exist, as per
168 // request by the embedder (of the content/ layer). Cannot be called for main
169 // frames.
170 //
171 // This only has an effect for <iframe> owner elements, and is a no-op when
172 // called on sub-frames hosted in <frame>, <object>, and <embed> elements.
173 void SetCollapsed(bool collapsed);
174
175 // Returns the origin of the last committed page in this frame.
176 // WARNING: To get the last committed origin for a particular
177 // RenderFrameHost, use RenderFrameHost::GetLastCommittedOrigin() instead,
178 // which will behave correctly even when the RenderFrameHost is not the
179 // current one for this frame (such as when it's pending deletion).
180 const url::Origin& current_origin() const {
181 return replication_state_.origin;
182 }
183
184 // Set the current origin and notify proxies about the update.
185 void SetCurrentOrigin(const url::Origin& origin,
186 bool is_potentially_trustworthy_unique_origin);
187
188 // Set the current name and notify proxies about the update.
189 void SetFrameName(const std::string& name, const std::string& unique_name);
190
191 // Add CSP headers to replication state, notify proxies about the update.
192 void AddContentSecurityPolicies(
193 std::vector<network::mojom::ContentSecurityPolicyHeaderPtr> headers);
194
195 // Sets the current insecure request policy, and notifies proxies about the
196 // update.
197 void SetInsecureRequestPolicy(blink::mojom::InsecureRequestPolicy policy);
198
199 // Sets the current set of insecure urls to upgrade, and notifies proxies
200 // about the update.
201 void SetInsecureNavigationsSet(
202 const std::vector<uint32_t>& insecure_navigations_set);
203
204 // Returns the latest frame policy (sandbox flags and container policy) for
205 // this frame. This includes flags inherited from parent frames and the latest
206 // flags from the <iframe> element hosting this frame. The returned policies
207 // may not yet have taken effect, since "sandbox" and "allow" attribute
208 // updates in an <iframe> element take effect on next navigation. To retrieve
209 // the currently active policy for this frame, use effective_frame_policy().
210 const blink::FramePolicy& pending_frame_policy() const {
211 return pending_frame_policy_;
212 }
213
214 // Update this frame's sandbox flags and container policy. This is called
215 // when a parent frame updates the "sandbox" attribute in the <iframe> element
216 // for this frame, or any of the attributes which affect the container policy
217 // ("allowfullscreen", "allowpaymentrequest", "allow", and "src".)
218 // These policies won't take effect until next navigation. If this frame's
219 // parent is itself sandboxed, the parent's sandbox flags are combined with
220 // those in |frame_policy|.
221 // Attempting to change the container policy on the main frame will have no
222 // effect.
223 void SetPendingFramePolicy(blink::FramePolicy frame_policy);
224
225 // Returns the currently active frame policy for this frame, including the
226 // sandbox flags which were present at the time the document was loaded, and
227 // the feature policy container policy, which is set by the iframe's
228 // allowfullscreen, allowpaymentrequest, and allow attributes, along with the
229 // origin of the iframe's src attribute (which may be different from the URL
230 // of the document currently loaded into the frame). This does not include
231 // policy changes that have been made by updating the containing iframe
232 // element attributes since the frame was last navigated; use
233 // pending_frame_policy() for those.
234 const blink::FramePolicy& effective_frame_policy() const {
235 return replication_state_.frame_policy;
236 }
237
238 // Set the frame_policy provided in function parameter as active frame policy,
239 // while leaving pending_frame_policy_ untouched.
240 bool CommitFramePolicy(const blink::FramePolicy& frame_policy);
241
242 const blink::mojom::FrameOwnerProperties& frame_owner_properties() {
243 return frame_owner_properties_;
244 }
245
246 void set_frame_owner_properties(
247 const blink::mojom::FrameOwnerProperties& frame_owner_properties) {
248 frame_owner_properties_ = frame_owner_properties;
249 }
250
251 const network::mojom::ContentSecurityPolicy* csp_attribute() {
252 return csp_attribute_.get();
253 }
254
255 void set_csp_attribute(
256 network::mojom::ContentSecurityPolicyPtr parsed_csp_attribute) {
257 csp_attribute_ = std::move(parsed_csp_attribute);
258 }
259
260 bool HasSameOrigin(const FrameTreeNode& node) const {
261 return replication_state_.origin.IsSameOriginWith(
262 node.replication_state_.origin);
263 }
264
265 const FrameReplicationState& current_replication_state() const {
266 return replication_state_;
267 }
268
269 RenderFrameHostImpl* current_frame_host() const {
270 return render_manager_.current_frame_host();
271 }
272
273 // Return the node immediately preceding this node in its parent's children,
274 // or nullptr if there is no such node.
275 FrameTreeNode* PreviousSibling() const;
276
277 // Return the node immediately following this node in its parent's children,
278 // or nullptr if there is no such node.
279 FrameTreeNode* NextSibling() const;
280
281 // Returns true if this node is in a loading state.
282 bool IsLoading() const;
283
284 NavigationRequest* navigation_request() { return navigation_request_.get(); }
285
286 // Transfers the ownership of the NavigationRequest to |render_frame_host|.
287 // From ReadyToCommit to DidCommit, the NavigationRequest is owned by the
288 // RenderFrameHost that is committing the navigation.
289 void TransferNavigationRequestOwnership(
290 RenderFrameHostImpl* render_frame_host);
291
292 // Takes ownership of |navigation_request| and makes it the current
293 // NavigationRequest of this frame. This corresponds to the start of a new
294 // navigation. If there was an ongoing navigation request before calling this
295 // function, it is canceled. |navigation_request| should not be null.
296 void CreatedNavigationRequest(
297 std::unique_ptr<NavigationRequest> navigation_request);
298
299 // Resets the current navigation request. If |keep_state| is true, any state
300 // created by the NavigationRequest (e.g. speculative RenderFrameHost,
301 // loading state) will not be reset by the function.
302 void ResetNavigationRequest(bool keep_state);
303
304 // A RenderFrameHost in this node started loading.
305 // |to_different_document| will be true unless the load is a fragment
306 // navigation, or triggered by history.pushState/replaceState.
307 // |was_previously_loading| is false if the FrameTree was not loading before.
308 // The caller is required to provide this boolean as the delegate should only
309 // be notified if the FrameTree went from non-loading to loading state.
310 // However, when it is called, the FrameTree should be in a loading state.
311 void DidStartLoading(bool to_different_document, bool was_previously_loading);
312
313 // A RenderFrameHost in this node stopped loading.
314 void DidStopLoading();
315
316 // The load progress for a RenderFrameHost in this node was updated to
317 // |load_progress|. This will notify the FrameTree which will in turn notify
318 // the WebContents.
319 void DidChangeLoadProgress(double load_progress);
320
321 // Called when the user directed the page to stop loading. Stops all loads
322 // happening in the FrameTreeNode. This method should be used with
323 // FrameTree::ForEach to stop all loads in the entire FrameTree.
324 bool StopLoading();
325
326 // Returns the time this frame was last focused.
327 base::TimeTicks last_focus_time() const { return last_focus_time_; }
328
329 // Called when this node becomes focused. Updates the node's last focused
330 // time and notifies observers.
331 void DidFocus();
332
333 // Called when the user closed the modal dialogue for BeforeUnload and
334 // cancelled the navigation. This should stop any load happening in the
335 // FrameTreeNode.
336 void BeforeUnloadCanceled();
337
338 // Returns the BlameContext associated with this node.
339 FrameTreeNodeBlameContext& blame_context() { return blame_context_; }
340
341 // Updates the user activation state in the browser frame tree and in the
342 // frame trees in all renderer processes except the renderer for this node
343 // (which initiated the update). Returns |false| if the update tries to
344 // consume an already consumed/expired transient state, |true| otherwise. See
345 // the comment on user_activation_state_ below.
346 //
347 // The |notification_type| parameter is used for histograms, only for the case
348 // |update_state == kNotifyActivation|.
349 bool UpdateUserActivationState(
350 blink::mojom::UserActivationUpdateType update_type,
351 blink::mojom::UserActivationNotificationType notification_type);
352
353 void OnSetHadStickyUserActivationBeforeNavigation(bool value);
354
355 // Returns the sandbox flags currently in effect for this frame. This includes
356 // flags inherited from parent frames, the currently active flags from the
357 // <iframe> element hosting this frame, as well as any flags set from a
358 // Content-Security-Policy HTTP header. This does not include flags that have
359 // have been updated in an <iframe> element but have not taken effect yet; use
360 // pending_frame_policy() for those. To see the flags which will take effect
361 // on navigation (which does not include the CSP-set flags), use
362 // effective_frame_policy().
363 network::mojom::WebSandboxFlags active_sandbox_flags() const {
364 return replication_state_.active_sandbox_flags;
365 }
366
367 // Updates the active sandbox flags in this frame, in response to a
368 // Content-Security-Policy header adding additional flags, in addition to
369 // those given to this frame by its parent, or in response to the
370 // Feature-Policy header being set. Note that on navigation, these updates
371 // will be cleared, and the flags in the pending frame policy will be applied
372 // to the frame.
373 void UpdateFramePolicyHeaders(
374 network::mojom::WebSandboxFlags sandbox_flags,
375 const blink::ParsedFeaturePolicy& parsed_header);
376
377 // Returns whether the frame received a user gesture on a previous navigation
378 // on the same eTLD+1.
379 bool has_received_user_gesture_before_nav() const {
380 return replication_state_.has_received_user_gesture_before_nav;
381 }
382
383 // When a tab is discarded, WebContents sets was_discarded on its
384 // root FrameTreeNode.
385 // In addition, when a child frame is created, this bit is passed on from
386 // parent to child.
387 // When a navigation request is created, was_discarded is passed on to the
388 // request and reset to false in FrameTreeNode.
389 void set_was_discarded() { was_discarded_ = true; }
390 bool was_discarded() const { return was_discarded_; }
391
392 // Returns the sticky bit of the User Activation v2 state of the
393 // |FrameTreeNode|.
394 bool HasStickyUserActivation() const {
395 return user_activation_state_.HasBeenActive();
396 }
397
398 // Returns the transient bit of the User Activation v2 state of the
399 // |FrameTreeNode|.
400 bool HasTransientUserActivation() {
401 return user_activation_state_.IsActive();
402 }
403
404 // Remove history entries for all frames created by script in this frame's
405 // subtree. If a frame created by a script is removed, then its history entry
406 // will never be reused - this saves memory.
407 void PruneChildFrameNavigationEntries(NavigationEntryImpl* entry);
408
409 blink::mojom::FrameOwnerElementType frame_owner_element_type() const {
410 return replication_state_.frame_owner_element_type;
411 }
412 // Only meaningful to call on a root frame. The value of |feature_state| will
413 // be nontrivial if there is an opener which is restricted in some of the
414 // feature policies.
415 void SetOpenerFeaturePolicyState(
416 const blink::FeaturePolicyFeatureState& feature_state);
417
418 void SetAdFrameType(blink::mojom::AdFrameType ad_frame_type);
419
420 private:
421 FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest,
422 ContainerPolicyDynamic);
423 FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest,
424 ContainerPolicySandboxDynamic);
425
426 class OpenerDestroyedObserver;
427
428 FrameTreeNode* GetSibling(int relative_offset) const;
429
430 // The |notification_type| parameter is used for histograms only.
431 bool NotifyUserActivation(
432 blink::mojom::UserActivationNotificationType notification_type);
433
434 bool ConsumeTransientUserActivation();
435
436 bool ClearUserActivation();
437
438 // Verify that the renderer process is allowed to set user activation on this
439 // frame by checking whether this frame's RenderWidgetHost had previously seen
440 // an input event that might lead to user activation. If user activation
441 // should be allowed, this returns true and also clears corresponding pending
442 // user activation state in the widget. Otherwise, this returns false.
443 bool VerifyUserActivation();
444
445 // The next available browser-global FrameTreeNode ID.
446 static int next_frame_tree_node_id_;
447
448 // The FrameTree that owns us.
449 FrameTree* frame_tree_; // not owned.
450
451 // Manages creation and swapping of RenderFrameHosts for this frame.
452 RenderFrameHostManager render_manager_;
453
454 // A browser-global identifier for the frame in the page, which stays stable
455 // even if the frame does a cross-process navigation.
456 const int frame_tree_node_id_;
457
458 // The RenderFrameHost owning this FrameTreeNode, which cannot change for the
459 // life of this FrameTreeNode. |nullptr| if this node is the root.
460 RenderFrameHostImpl* const parent_;
461
462 // Number of edges from this node to the root. 0 if this is the root.
463 const unsigned int depth_;
464
465 // The frame that opened this frame, if any. Will be set to null if the
466 // opener is closed, or if this frame disowns its opener by setting its
467 // window.opener to null.
468 FrameTreeNode* opener_;
469
470 // An observer that clears this node's |opener_| if the opener is destroyed.
471 // This observer is added to the |opener_|'s observer list when the |opener_|
472 // is set to a non-null node, and it is removed from that list when |opener_|
473 // changes or when this node is destroyed. It is also cleared if |opener_|
474 // is disowned.
475 std::unique_ptr<OpenerDestroyedObserver> opener_observer_;
476
477 // The frame that opened this frame, if any. Contrary to opener_, this
478 // cannot be changed unless the original opener is destroyed.
479 FrameTreeNode* original_opener_;
480
481 // An observer that clears this node's |original_opener_| if the opener is
482 // destroyed.
483 std::unique_ptr<OpenerDestroyedObserver> original_opener_observer_;
484
485 // Whether this frame has committed any real load, replacing its initial
486 // about:blank page.
487 bool has_committed_real_load_;
488
489 // Whether the frame's owner element in the parent document is collapsed.
490 bool is_collapsed_;
491
492 // Track information that needs to be replicated to processes that have
493 // proxies for this frame.
494 FrameReplicationState replication_state_;
495
496 // Track the pending sandbox flags and container policy for this frame. When a
497 // parent frame dynamically updates 'sandbox', 'allow', 'allowfullscreen',
498 // 'allowpaymentrequest' or 'src' attributes, the updated policy for the frame
499 // is stored here, and transferred into replication_state_.frame_policy when
500 // they take effect on the next frame navigation.
501 blink::FramePolicy pending_frame_policy_;
502
503 // Whether the frame was created by javascript. This is useful to prune
504 // history entries when the frame is removed (because frames created by
505 // scripts are never recreated with the same unique name - see
506 // https://crbug.com/500260).
507 bool is_created_by_script_;
508
509 // Used for devtools instrumentation and trace-ability. The token is
510 // propagated to Blink's LocalFrame and both Blink and content/
511 // can tag calls and requests with this token in order to attribute them
512 // to the context frame.
513 // |devtools_frame_token_| is only defined by the browser process and is never
514 // sent back from the renderer in the control calls. It should be never used
515 // to look up the FrameTreeNode instance.
516 base::UnguessableToken devtools_frame_token_;
517
518 // Tracks the scrolling and margin properties for this frame. These
519 // properties affect the child renderer but are stored on its parent's
520 // frame element. When this frame's parent dynamically updates these
521 // properties, we update them here too.
522 //
523 // Note that dynamic updates only take effect on the next frame navigation.
524 blink::mojom::FrameOwnerProperties frame_owner_properties_;
525
526 // Contains the current parsed value of the 'csp' attribute of this frame.
527 network::mojom::ContentSecurityPolicyPtr csp_attribute_;
528
529 // Owns an ongoing NavigationRequest until it is ready to commit. It will then
530 // be reset and a RenderFrameHost will be responsible for the navigation.
531 std::unique_ptr<NavigationRequest> navigation_request_;
532
533 // List of objects observing this FrameTreeNode.
534 base::ObserverList<Observer>::Unchecked observers_;
535
536 base::TimeTicks last_focus_time_;
537
538 bool was_discarded_;
539
540 // The user activation state of the current frame. See |UserActivationState|
541 // for details on how this state is maintained.
542 blink::UserActivationState user_activation_state_;
543
544 // A helper for tracing the snapshots of this FrameTreeNode and attributing
545 // browser process activities to this node (when possible). It is unrelated
546 // to the core logic of FrameTreeNode.
547 FrameTreeNodeBlameContext blame_context_;
548
549 DISALLOW_COPY_AND_ASSIGN(FrameTreeNode);
550};
551
552} // namespace content
553
554#endif // CONTENT_BROWSER_RENDERER_HOST_FRAME_TREE_NODE_H_