Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(657)

Side by Side Diff: content/browser/browsing_data/clear_site_data_throttle.cc

Issue 2368923003: Support the Clear-Site-Data header on resource requests (Closed)
Patch Set: Wait for SW activation. Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/browsing_data/clear_site_data_throttle.h" 5 #include "content/browser/browsing_data/clear_site_data_throttle.h"
6 6
7 #include "base/command_line.h" 7 #include "base/command_line.h"
8 #include "base/json/json_reader.h" 8 #include "base/json/json_reader.h"
9 #include "base/json/json_string_value_serializer.h" 9 #include "base/json/json_string_value_serializer.h"
10 #include "base/memory/ptr_util.h" 10 #include "base/memory/ptr_util.h"
11 #include "base/metrics/histogram_macros.h" 11 #include "base/metrics/histogram_macros.h"
12 #include "base/strings/string_util.h" 12 #include "base/strings/string_util.h"
13 #include "base/strings/stringprintf.h" 13 #include "base/strings/stringprintf.h"
14 #include "base/values.h" 14 #include "base/values.h"
15 #include "content/browser/frame_host/navigation_handle_impl.h" 15 #include "content/browser/service_worker/service_worker_response_info.h"
16 #include "content/public/browser/browser_context.h" 16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/browser_thread.h"
17 #include "content/public/browser/content_browser_client.h" 18 #include "content/public/browser/content_browser_client.h"
18 #include "content/public/browser/navigation_handle.h" 19 #include "content/public/browser/render_frame_host.h"
20 #include "content/public/browser/resource_controller.h"
21 #include "content/public/browser/storage_partition.h"
19 #include "content/public/browser/web_contents.h" 22 #include "content/public/browser/web_contents.h"
20 #include "content/public/common/content_client.h" 23 #include "content/public/common/content_client.h"
21 #include "content/public/common/content_switches.h" 24 #include "content/public/common/content_switches.h"
22 #include "content/public/common/origin_util.h" 25 #include "content/public/common/origin_util.h"
26 #include "content/public/common/resource_response_info.h"
27 #include "net/base/load_flags.h"
23 #include "net/http/http_response_headers.h" 28 #include "net/http/http_response_headers.h"
29 #include "net/url_request/redirect_info.h"
24 #include "url/gurl.h" 30 #include "url/gurl.h"
25 #include "url/origin.h" 31 #include "url/origin.h"
26 32
27 namespace content { 33 namespace content {
28 34
29 namespace { 35 namespace {
30 36
37 static const char* kNameForLogging = "ClearSiteDataThrottle";
38
31 static const char* kClearSiteDataHeader = "Clear-Site-Data"; 39 static const char* kClearSiteDataHeader = "Clear-Site-Data";
32 40
33 static const char* kTypesKey = "types"; 41 static const char* kTypesKey = "types";
34 42
35 // Pretty-printed log output. 43 // Pretty-printed log output.
36 static const char* kConsoleMessagePrefix = "Clear-Site-Data header on '%s': %s"; 44 static const char* kConsoleMessagePrefix = "Clear-Site-Data header on '%s': %s";
37 static const char* kClearingOneType = "Clearing %s."; 45 static const char* kClearingOneType = "Clearing %s.";
38 static const char* kClearingTwoTypes = "Clearing %s and %s."; 46 static const char* kClearingTwoTypes = "Clearing %s and %s.";
39 static const char* kClearingThreeTypes = "Clearing %s, %s, and %s."; 47 static const char* kClearingThreeTypes = "Clearing %s, %s, and %s.";
40 48
(...skipping 10 matching lines...) Expand all
51 switches::kEnableExperimentalWebPlatformFeatures); 59 switches::kEnableExperimentalWebPlatformFeatures);
52 } 60 }
53 61
54 // Represents the parameters as a single number to be recorded in a histogram. 62 // Represents the parameters as a single number to be recorded in a histogram.
55 int ParametersMask(bool clear_cookies, bool clear_storage, bool clear_cache) { 63 int ParametersMask(bool clear_cookies, bool clear_storage, bool clear_cache) {
56 return static_cast<int>(clear_cookies) * (1 << 0) + 64 return static_cast<int>(clear_cookies) * (1 << 0) +
57 static_cast<int>(clear_storage) * (1 << 1) + 65 static_cast<int>(clear_storage) * (1 << 1) +
58 static_cast<int>(clear_cache) * (1 << 2); 66 static_cast<int>(clear_cache) * (1 << 2);
59 } 67 }
60 68
61 } // namespace 69 // A helper function to pass an IO thread callback to a method called on
62 70 // the UI thread.
63 // static 71 void JumpFromUIToIOThread(const base::Closure& callback) {
64 std::unique_ptr<NavigationThrottle> 72 DCHECK_CURRENTLY_ON(BrowserThread::UI);
65 ClearSiteDataThrottle::CreateThrottleForNavigation(NavigationHandle* handle) { 73 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, callback);
66 if (AreExperimentalFeaturesEnabled())
67 return base::WrapUnique(new ClearSiteDataThrottle(handle));
68
69 return std::unique_ptr<NavigationThrottle>();
70 } 74 }
71 75
72 ClearSiteDataThrottle::ClearSiteDataThrottle( 76 // Finds the BrowserContext associated with the request and requests
73 NavigationHandle* navigation_handle) 77 // the actual clearing of data for |origin|. The datatypes to be deleted
74 : NavigationThrottle(navigation_handle), 78 // are determined by |clear_cookies|, |clear_storage|, and |clear_cache|.
75 clearing_in_progress_(false), 79 // |web_contents_getter| identifies the WebContents from which the request
76 weak_ptr_factory_(this) {} 80 // originated. Must be run on the UI thread. The |callback| will be executed
81 // on the IO thread.
82 void ClearSiteDataOnUIThread(
83 const ResourceRequestInfo::WebContentsGetter& web_contents_getter,
84 url::Origin origin,
85 bool clear_cookies,
86 bool clear_storage,
87 bool clear_cache,
88 const base::Closure& callback) {
89 DCHECK_CURRENTLY_ON(BrowserThread::UI);
77 90
78 ClearSiteDataThrottle::~ClearSiteDataThrottle() { 91 WebContents* web_contents = web_contents_getter.Run();
79 // At the end of the navigation we finally have access to the correct 92 if (!web_contents)
80 // RenderFrameHost. Output the cached console messages. Prefix each sequence 93 return;
81 // of messages belonging to the same URL with |kConsoleMessagePrefix|. 94
95 BrowserContext* browser_context = web_contents->GetBrowserContext();
96
97 GetContentClient()->browser()->ClearSiteData(
98 browser_context, origin, clear_cookies, clear_storage, clear_cache,
99 base::Bind(&JumpFromUIToIOThread, callback));
100 }
101
102 // Outputs |messages| to the console of WebContents retrieved from
103 // |web_contents_getter|. Must be run on the UI thread.
104 void OutputConsoleMessagesOnUIThread(
105 const ResourceRequestInfo::WebContentsGetter& web_contents_getter,
106 const std::vector<ClearSiteDataThrottle::ConsoleMessage>& messages) {
107 DCHECK_CURRENTLY_ON(BrowserThread::UI);
108
109 WebContents* web_contents = web_contents_getter.Run();
110 if (!web_contents)
111 return;
112
82 GURL last_seen_url; 113 GURL last_seen_url;
83 for (const ConsoleMessage& message : messages_) { 114 for (const ClearSiteDataThrottle::ConsoleMessage& message : messages) {
84 if (message.url == last_seen_url) { 115 if (message.url == last_seen_url) {
85 navigation_handle()->GetRenderFrameHost()->AddMessageToConsole( 116 web_contents->GetMainFrame()->AddMessageToConsole(message.level,
86 message.level, message.text); 117 message.text);
87 } else { 118 } else {
88 navigation_handle()->GetRenderFrameHost()->AddMessageToConsole( 119 web_contents->GetMainFrame()->AddMessageToConsole(
89 message.level, 120 message.level,
90 base::StringPrintf(kConsoleMessagePrefix, message.url.spec().c_str(), 121 base::StringPrintf(kConsoleMessagePrefix, message.url.spec().c_str(),
91 message.text.c_str())); 122 message.text.c_str()));
92 } 123 }
93 124
94 last_seen_url = message.url; 125 last_seen_url = message.url;
95 } 126 }
96 } 127 }
97 128
98 ClearSiteDataThrottle::ThrottleCheckResult 129 } // namespace
99 ClearSiteDataThrottle::WillStartRequest() { 130
100 current_url_ = navigation_handle()->GetURL(); 131 // static
101 return PROCEED; 132 std::unique_ptr<ResourceThrottle>
133 ClearSiteDataThrottle::CreateThrottleForRequest(net::URLRequest* request) {
134 // This is an experimental feature.
135 if (!AreExperimentalFeaturesEnabled())
136 return std::unique_ptr<ResourceThrottle>();
137
138 // The LOAD_DO_NOT_SAVE_COOKIES flag prohibits the request from doing any
139 // modification to cookies.
140 std::unique_ptr<base::Value> value = request->GetStateAsValue();
141 const base::DictionaryValue* state;
142 DCHECK(value->GetAsDictionary(&state));
143 int load_flags = 0;
144 bool success =
145 state->GetIntegerWithoutPathExpansion("load_flags", &load_flags);
146 DCHECK(success);
mmenke 2016/10/20 19:03:10 This is all just request->load_flags()...May be si
msramek 2016/10/21 13:36:00 Good to know! I moved this to HandleHeader(). That
147 if (load_flags & net::LOAD_DO_NOT_SAVE_COOKIES)
148 return std::unique_ptr<ResourceThrottle>();
149
150 // The throttle has no purpose if the request has no ResourceRequestInfo,
151 // because we won't be able to determine whose data should be deleted.
152 if (!ResourceRequestInfo::ForRequest(request))
153 return std::unique_ptr<ResourceThrottle>();
154
155 return base::WrapUnique(new ClearSiteDataThrottle(request));
102 } 156 }
103 157
104 ClearSiteDataThrottle::ThrottleCheckResult 158 ClearSiteDataThrottle::ClearSiteDataThrottle(net::URLRequest* request)
105 ClearSiteDataThrottle::WillRedirectRequest() { 159 : request_(request),
160 clearing_in_progress_(false),
161 weak_ptr_factory_(this) {}
162
163 ClearSiteDataThrottle::~ClearSiteDataThrottle() {
164 // Output the cached console messages. Prefix each sequence of messages
165 // belonging to the same URL with |kConsoleMessagePrefix|. We output console
166 // messages when the request is finished rather than in real time, since in
167 // case of navigations swapping RenderFrameHost would cause the outputs to
168 // disappear.
169 if (messages_.empty())
170 return;
171
172 DCHECK_CURRENTLY_ON(BrowserThread::IO);
173 BrowserThread::PostTask(
174 BrowserThread::UI, FROM_HERE,
175 base::Bind(&OutputConsoleMessagesOnUIThread,
176 ResourceRequestInfo::ForRequest(request_)
177 ->GetWebContentsGetterForRequest(),
178 std::move(messages_)));
179 }
180
181 void ClearSiteDataThrottle::WillStartRequest(bool* defer) {
182 current_url_ = request_->original_url();
183 *defer = false;
184 }
185
186 void ClearSiteDataThrottle::WillRedirectRequest(
187 const net::RedirectInfo& redirect_info,
188 bool* defer) {
106 // We are processing a redirect from url1 to url2. GetResponseHeaders() 189 // We are processing a redirect from url1 to url2. GetResponseHeaders()
107 // contains headers from url1, but GetURL() is already equal to url2. Handle 190 // contains headers from url1, but GetURL() is already equal to url2. Handle
108 // the headers before updating the URL, so that |current_url_| corresponds 191 // the headers before updating the URL, so that |current_url_| corresponds
109 // to the URL that sent the headers. 192 // to the URL that sent the headers.
110 HandleHeader(); 193 HandleHeader();
111 current_url_ = navigation_handle()->GetURL(); 194 current_url_ = redirect_info.new_url;
112 195 *defer = clearing_in_progress_;
mmenke 2016/10/20 19:03:10 I think the code is easier to follow if HandleHead
msramek 2016/10/21 13:36:00 Done. Since the "success" of HandleHeader() is equ
113 return clearing_in_progress_ ? DEFER : PROCEED;
114 } 196 }
115 197
116 ClearSiteDataThrottle::ThrottleCheckResult 198 void ClearSiteDataThrottle::WillProcessResponse(bool* defer) {
117 ClearSiteDataThrottle::WillProcessResponse() {
118 HandleHeader(); 199 HandleHeader();
119 return clearing_in_progress_ ? DEFER : PROCEED; 200 *defer = clearing_in_progress_;
mmenke 2016/10/20 19:03:10 This behavior should probably be documented in the
msramek 2016/10/21 13:36:00 It is mentioned in the class-level comment. Or do
mmenke 2016/10/21 15:16:20 Sorry, I missed that.
201 }
202
203 const char* ClearSiteDataThrottle::GetNameForLogging() const {
204 return kNameForLogging;
120 } 205 }
121 206
122 void ClearSiteDataThrottle::HandleHeader() { 207 void ClearSiteDataThrottle::HandleHeader() {
123 NavigationHandleImpl* handle = 208 const net::HttpResponseHeaders* headers = request_->response_headers();
124 static_cast<NavigationHandleImpl*>(navigation_handle());
125 const net::HttpResponseHeaders* headers = handle->GetResponseHeaders();
126 209
127 if (!headers || !headers->HasHeader(kClearSiteDataHeader)) 210 if (!headers || !headers->HasHeader(kClearSiteDataHeader))
128 return; 211 return;
129 212
130 // Only accept the header on secure origins. 213 // Only accept the header on secure origins.
131 if (!IsOriginSecure(current_url_)) { 214 if (!IsOriginSecure(current_url_)) {
132 ConsoleLog(&messages_, current_url_, "Not supported for insecure origins.", 215 ConsoleLog(&messages_, current_url_, "Not supported for insecure origins.",
133 CONSOLE_MESSAGE_LEVEL_ERROR); 216 CONSOLE_MESSAGE_LEVEL_ERROR);
134 return; 217 return;
135 } 218 }
136 219
220 // Service workers can handle fetches of third-party resources and inject
221 // arbitrary headers. Ignore responses that came from a service worker,
222 // as supporting Clear-Site-Data would give them the power to delete data from
223 // any website.
224 const ServiceWorkerResponseInfo* response_info =
225 ServiceWorkerResponseInfo::ForRequest(request_);
226 if (response_info) {
227 ResourceResponseInfo extra_response_info;
228 response_info->GetExtraResponseInfo(&extra_response_info);
229
230 if (extra_response_info.was_fetched_via_service_worker) {
231 ConsoleLog(&messages_, current_url_,
232 "Ignoring, as the response came from a service worker.",
233 CONSOLE_MESSAGE_LEVEL_ERROR);
234 return;
235 }
236 }
237
137 std::string header_value; 238 std::string header_value;
138 headers->GetNormalizedHeader(kClearSiteDataHeader, &header_value); 239 headers->GetNormalizedHeader(kClearSiteDataHeader, &header_value);
mmenke 2016/10/20 19:03:11 Rather than two searches for the header, can just
msramek 2016/10/21 13:36:00 Done. Good catch.
139 240
140 bool clear_cookies; 241 bool clear_cookies;
141 bool clear_storage; 242 bool clear_storage;
142 bool clear_cache; 243 bool clear_cache;
143 244
144 if (!ParseHeader(header_value, &clear_cookies, &clear_storage, &clear_cache, 245 if (!ParseHeader(header_value, &clear_cookies, &clear_storage, &clear_cache,
145 &messages_)) { 246 &messages_)) {
146 return; 247 return;
147 } 248 }
148 249
149 // Record the call parameters. 250 // Record the call parameters.
150 UMA_HISTOGRAM_ENUMERATION( 251 UMA_HISTOGRAM_ENUMERATION(
151 "Navigation.ClearSiteData.Parameters", 252 "Navigation.ClearSiteData.Parameters",
152 ParametersMask(clear_cookies, clear_storage, clear_cache), (1 << 3)); 253 ParametersMask(clear_cookies, clear_storage, clear_cache), (1 << 3));
153 254
154 // If the header is valid, clear the data for this browser context and origin. 255 // If the header is valid, clear the data for this browser context and origin.
155 BrowserContext* browser_context =
156 navigation_handle()->GetWebContents()->GetBrowserContext();
157 url::Origin origin(current_url_); 256 url::Origin origin(current_url_);
158
159 if (origin.unique()) { 257 if (origin.unique()) {
mmenke 2016/10/20 19:03:10 Should this go up with the IsOriginSecure check?
msramek 2016/10/21 13:36:00 Done. Yeah, makes sense. Now that I'm looking at
mmenke 2016/10/21 15:16:20 File origins are secure and unique (Though they do
160 ConsoleLog(&messages_, current_url_, "Not supported for unique origins.", 258 ConsoleLog(&messages_, current_url_, "Not supported for unique origins.",
161 CONSOLE_MESSAGE_LEVEL_ERROR); 259 CONSOLE_MESSAGE_LEVEL_ERROR);
162 return; 260 return;
163 } 261 }
164 262
165 clearing_in_progress_ = true; 263 clearing_in_progress_ = true;
166 clearing_started_ = base::TimeTicks::Now(); 264 clearing_started_ = base::TimeTicks::Now();
167 GetContentClient()->browser()->ClearSiteData( 265
168 browser_context, origin, clear_cookies, clear_storage, clear_cache, 266 DCHECK_CURRENTLY_ON(BrowserThread::IO);
169 base::Bind(&ClearSiteDataThrottle::TaskFinished, 267 BrowserThread::PostTask(
170 weak_ptr_factory_.GetWeakPtr())); 268 BrowserThread::UI, FROM_HERE,
269 base::Bind(&ClearSiteDataOnUIThread,
270 ResourceRequestInfo::ForRequest(request_)
271 ->GetWebContentsGetterForRequest(),
272 origin, clear_cookies, clear_storage, clear_cache,
273 base::Bind(&ClearSiteDataThrottle::TaskFinished,
274 weak_ptr_factory_.GetWeakPtr())));
171 } 275 }
172 276
173 bool ClearSiteDataThrottle::ParseHeader(const std::string& header, 277 bool ClearSiteDataThrottle::ParseHeader(const std::string& header,
174 bool* clear_cookies, 278 bool* clear_cookies,
175 bool* clear_storage, 279 bool* clear_storage,
176 bool* clear_cache, 280 bool* clear_cache,
177 std::vector<ConsoleMessage>* messages) { 281 std::vector<ConsoleMessage>* messages) {
178 if (!base::IsStringASCII(header)) { 282 if (!base::IsStringASCII(header)) {
179 ConsoleLog(messages, current_url_, "Must only contain ASCII characters.", 283 ConsoleLog(messages, current_url_, "Must only contain ASCII characters.",
180 CONSOLE_MESSAGE_LEVEL_ERROR); 284 CONSOLE_MESSAGE_LEVEL_ERROR);
(...skipping 80 matching lines...) Expand 10 before | Expand all | Expand 10 after
261 break; 365 break;
262 default: 366 default:
263 NOTREACHED(); 367 NOTREACHED();
264 } 368 }
265 ConsoleLog(messages, current_url_, output, CONSOLE_MESSAGE_LEVEL_LOG); 369 ConsoleLog(messages, current_url_, output, CONSOLE_MESSAGE_LEVEL_LOG);
266 370
267 return true; 371 return true;
268 } 372 }
269 373
270 void ClearSiteDataThrottle::TaskFinished() { 374 void ClearSiteDataThrottle::TaskFinished() {
375 DCHECK_CURRENTLY_ON(BrowserThread::IO);
271 DCHECK(clearing_in_progress_); 376 DCHECK(clearing_in_progress_);
272 clearing_in_progress_ = false; 377 clearing_in_progress_ = false;
273 378
274 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.ClearSiteData.Duration", 379 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.ClearSiteData.Duration",
275 base::TimeTicks::Now() - clearing_started_, 380 base::TimeTicks::Now() - clearing_started_,
276 base::TimeDelta::FromMilliseconds(1), 381 base::TimeDelta::FromMilliseconds(1),
277 base::TimeDelta::FromSeconds(1), 50); 382 base::TimeDelta::FromSeconds(1), 50);
278 383
279 navigation_handle()->Resume(); 384 controller()->Resume();
280 } 385 }
281 386
282 } // namespace content 387 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698