OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2017 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 #include "chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h" | |
6 | |
7 #include <string> | |
8 #include <utility> | |
9 | |
10 #include "base/callback.h" | |
11 #include "base/command_line.h" | |
12 #include "base/json/json_reader.h" | |
13 #include "base/memory/ptr_util.h" | |
14 #include "base/strings/stringprintf.h" | |
15 #include "base/values.h" | |
16 #include "chrome/browser/browser_process.h" | |
17 #include "chrome/browser/search/one_google_bar/one_google_bar_data.h" | |
18 #include "chrome/common/chrome_content_client.h" | |
19 #include "components/google/core/browser/google_url_tracker.h" | |
20 #include "components/signin/core/browser/access_token_fetcher.h" | |
21 #include "components/signin/core/browser/signin_manager.h" | |
22 #include "components/variations/net/variations_http_headers.h" | |
23 #include "google_apis/gaia/oauth2_token_service.h" | |
24 #include "google_apis/google_api_keys.h" | |
25 #include "net/base/load_flags.h" | |
26 #include "net/http/http_status_code.h" | |
27 #include "net/url_request/url_fetcher.h" | |
28 #include "net/url_request/url_fetcher_delegate.h" | |
29 | |
30 namespace { | |
31 | |
32 const char kApiUrl[] = "https://onegoogle-pa.googleapis.com/v1/getbar"; | |
33 | |
34 const char kApiKeyFormat[] = "?key=%s"; | |
35 | |
36 const char kApiScope[] = "https://www.googleapis.com/auth/onegoogle.readonly"; | |
37 const char kAuthorizationRequestHeaderFormat[] = "Bearer %s"; | |
38 | |
39 const char kRequestBodyFormat[] = R"json({ | |
40 "subproduct": 243, | |
41 "enable_multilogin": true, | |
42 "user_agent": "%s", | |
43 "accept_language": "%s", | |
44 "original_request_url": "%s", | |
45 "material_options": { | |
46 "page_title": " ", | |
47 "position_fixed": true, | |
48 "styling_options": { | |
49 "background_color": { "alpha": { "value": 0 } } | |
50 }, | |
51 "disable_moving_userpanel_to_menu": true | |
52 } | |
53 })json"; | |
54 | |
55 const char kResponsePreamble[] = ")]}'"; | |
56 | |
57 // This namespace contains helpers to extract SafeHtml-wrapped strings (see | |
58 // https://github.com/google/safe-html-types) from the response json. If there | |
59 // is ever a C++ version of the SafeHtml types, we should consider using that | |
60 // instead of these custom functions. | |
61 namespace safe_html { | |
62 | |
63 bool GetImpl(const base::DictionaryValue& dict, | |
64 const std::string& name, | |
65 const std::string& wrapped_field_name, | |
66 std::string* out) { | |
67 const base::DictionaryValue* value = nullptr; | |
68 if (!dict.GetDictionary(name, &value)) { | |
69 out->clear(); | |
70 return false; | |
71 } | |
72 | |
73 if (!value->GetString(wrapped_field_name, out)) { | |
74 out->clear(); | |
75 return false; | |
76 } | |
77 | |
78 return true; | |
79 } | |
80 | |
81 bool GetHtml(const base::DictionaryValue& dict, | |
82 const std::string& name, | |
83 std::string* out) { | |
84 return GetImpl(dict, name, "privateDoNotAccessOrElseSafeHtmlWrappedValue", | |
85 out); | |
86 } | |
87 | |
88 bool GetScript(const base::DictionaryValue& dict, | |
89 const std::string& name, | |
90 std::string* out) { | |
91 return GetImpl(dict, name, "privateDoNotAccessOrElseSafeScriptWrappedValue", | |
92 out); | |
93 } | |
94 | |
95 bool GetStyleSheet(const base::DictionaryValue& dict, | |
96 const std::string& name, | |
97 std::string* out) { | |
98 return GetImpl(dict, name, | |
99 "privateDoNotAccessOrElseSafeStyleSheetWrappedValue", out); | |
100 } | |
101 | |
102 } // namespace safe_html | |
103 | |
104 } // namespace | |
105 | |
106 class OneGoogleBarFetcherImpl::AuthenticatedURLFetcher | |
107 : public net::URLFetcherDelegate { | |
108 public: | |
109 using FetchDoneCallback = base::OnceCallback<void(const net::URLFetcher*)>; | |
110 | |
111 AuthenticatedURLFetcher(SigninManagerBase* signin_manager, | |
112 OAuth2TokenService* token_service, | |
113 net::URLRequestContextGetter* request_context, | |
114 const GURL& google_base_url, | |
115 FetchDoneCallback callback); | |
116 ~AuthenticatedURLFetcher() override = default; | |
117 | |
118 void Start(); | |
119 | |
120 private: | |
121 GURL GetApiUrl(bool use_oauth) const; | |
122 std::string GetRequestBody() const; | |
123 std::string GetExtraRequestHeaders(const GURL& url, | |
124 const std::string& access_token) const; | |
125 | |
126 void GotAccessToken(const GoogleServiceAuthError& error, | |
127 const std::string& access_token); | |
128 | |
129 // URLFetcherDelegate implementation. | |
130 void OnURLFetchComplete(const net::URLFetcher* source) override; | |
131 | |
132 SigninManagerBase* const signin_manager_; | |
133 OAuth2TokenService* const token_service_; | |
134 net::URLRequestContextGetter* const request_context_; | |
135 const GURL google_base_url_; | |
136 | |
137 FetchDoneCallback callback_; | |
138 | |
139 std::unique_ptr<AccessTokenFetcher> token_fetcher_; | |
140 | |
141 // The underlying URLFetcher which does the actual fetch. | |
142 std::unique_ptr<net::URLFetcher> url_fetcher_; | |
143 }; | |
144 | |
145 OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::AuthenticatedURLFetcher( | |
146 SigninManagerBase* signin_manager, | |
147 OAuth2TokenService* token_service, | |
148 net::URLRequestContextGetter* request_context, | |
149 const GURL& google_base_url, | |
150 FetchDoneCallback callback) | |
151 : signin_manager_(signin_manager), | |
152 token_service_(token_service), | |
153 request_context_(request_context), | |
154 google_base_url_(google_base_url), | |
155 callback_(std::move(callback)) {} | |
156 | |
157 void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::Start() { | |
158 if (!signin_manager_->IsAuthenticated()) { | |
159 GotAccessToken(GoogleServiceAuthError::AuthErrorNone(), std::string()); | |
160 return; | |
161 } | |
162 OAuth2TokenService::ScopeSet scopes; | |
163 scopes.insert(kApiScope); | |
164 token_fetcher_ = base::MakeUnique<AccessTokenFetcher>( | |
165 "one_google", signin_manager_, token_service_, scopes, | |
166 base::BindOnce(&AuthenticatedURLFetcher::GotAccessToken, | |
167 base::Unretained(this))); | |
168 } | |
169 | |
170 GURL OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetApiUrl( | |
171 bool use_oauth) const { | |
172 std::string api_url(kApiUrl); | |
173 // TODO(treib): Attach to feature instead of cmdline. | |
174 base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); | |
175 if (cmdline->HasSwitch("one-google-api-url")) | |
176 api_url = cmdline->GetSwitchValueASCII("one-google-api-url"); | |
177 // Append the API key only for unauthenticated requests. | |
178 if (!use_oauth) { | |
179 api_url += | |
180 base::StringPrintf(kApiKeyFormat, google_apis::GetAPIKey().c_str()); | |
181 } | |
182 | |
183 return GURL(api_url); | |
184 } | |
185 | |
186 std::string OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetRequestBody() | |
187 const { | |
188 // TODO(treib): Attach to feature instead of cmdline. | |
189 base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); | |
190 if (cmdline->HasSwitch("one-google-bar-options")) | |
191 return cmdline->GetSwitchValueASCII("one-google-bar-options"); | |
192 | |
193 return base::StringPrintf(kRequestBodyFormat, GetUserAgent().c_str(), | |
sfiera
2017/04/13 09:42:51
Do we know for sure that these values don't need a
Marc Treib
2017/04/13 10:23:53
Good point - not sure, no. It's probably better an
| |
194 g_browser_process->GetApplicationLocale().c_str(), | |
195 google_base_url_.spec().c_str()); | |
196 } | |
197 | |
198 std::string | |
199 OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetExtraRequestHeaders( | |
200 const GURL& url, | |
201 const std::string& access_token) const { | |
202 net::HttpRequestHeaders headers; | |
203 headers.SetHeader("Content-Type", "application/json; charset=UTF-8"); | |
204 if (!access_token.empty()) { | |
205 headers.SetHeader("Authorization", | |
206 base::StringPrintf(kAuthorizationRequestHeaderFormat, | |
207 access_token.c_str())); | |
208 } | |
209 // Note: It's OK to pass |is_signed_in| false if it's unknown, as it does | |
210 // not affect transmission of experiments coming from the variations server. | |
211 variations::AppendVariationHeaders(url, | |
212 /*incognito=*/false, /*uma_enabled*/ false, | |
sfiera
2017/04/13 09:42:51
missing an =
Marc Treib
2017/04/13 10:23:53
Done.
| |
213 /*is_signed_in=*/false, &headers); | |
214 return headers.ToString(); | |
215 } | |
216 | |
217 void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GotAccessToken( | |
218 const GoogleServiceAuthError& error, | |
219 const std::string& access_token) { | |
220 // Delete the token fetcher after we leave this method. | |
221 std::unique_ptr<AccessTokenFetcher> deleter(std::move(token_fetcher_)); | |
222 | |
223 bool use_oauth = !access_token.empty(); | |
224 GURL url = GetApiUrl(use_oauth); | |
225 url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::POST, this); | |
226 url_fetcher_->SetRequestContext(request_context_); | |
227 | |
228 url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_AUTH_DATA | | |
229 net::LOAD_DO_NOT_SEND_COOKIES | | |
230 net::LOAD_DO_NOT_SAVE_COOKIES); | |
231 url_fetcher_->SetUploadData("application/json", GetRequestBody()); | |
232 url_fetcher_->SetExtraRequestHeaders( | |
233 GetExtraRequestHeaders(url, access_token)); | |
234 | |
235 url_fetcher_->Start(); | |
236 } | |
237 | |
238 void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::OnURLFetchComplete( | |
239 const net::URLFetcher* source) { | |
240 std::move(callback_).Run(source); | |
241 } | |
242 | |
243 OneGoogleBarFetcherImpl::OneGoogleBarFetcherImpl( | |
244 SigninManagerBase* signin_manager, | |
245 OAuth2TokenService* token_service, | |
246 net::URLRequestContextGetter* request_context, | |
247 GoogleURLTracker* google_url_tracker) | |
248 : signin_manager_(signin_manager), | |
249 token_service_(token_service), | |
250 request_context_(request_context), | |
251 google_url_tracker_(google_url_tracker) {} | |
252 | |
253 OneGoogleBarFetcherImpl::~OneGoogleBarFetcherImpl() = default; | |
254 | |
255 void OneGoogleBarFetcherImpl::Fetch(OneGoogleCallback callback) { | |
256 callbacks_.push_back(std::move(callback)); | |
257 IssueRequestIfNoneOngoing(); | |
258 } | |
259 | |
260 void OneGoogleBarFetcherImpl::IssueRequestIfNoneOngoing() { | |
261 // If there is an ongoing request, let it complete. | |
262 if (pending_request_.get()) | |
263 return; | |
264 | |
265 pending_request_ = base::MakeUnique<AuthenticatedURLFetcher>( | |
266 signin_manager_, token_service_, request_context_, | |
267 google_url_tracker_->google_url(), | |
268 base::BindOnce(&OneGoogleBarFetcherImpl::FetchDone, | |
269 base::Unretained(this))); | |
270 pending_request_->Start(); | |
271 } | |
272 | |
273 void OneGoogleBarFetcherImpl::FetchDone(const net::URLFetcher* source) { | |
274 // The fetcher will be deleted when the request is handled. | |
275 std::unique_ptr<AuthenticatedURLFetcher> deleter(std::move(pending_request_)); | |
276 | |
277 const net::URLRequestStatus& request_status = source->GetStatus(); | |
278 if (request_status.status() != net::URLRequestStatus::SUCCESS) { | |
279 // This represents network errors (i.e. the server did not provide a | |
280 // response). | |
281 DLOG(WARNING) << "Request failed with error: " << request_status.error() | |
282 << ": " << net::ErrorToString(request_status.error()); | |
283 Respond(base::nullopt); | |
284 return; | |
285 } | |
286 | |
287 const int response_code = source->GetResponseCode(); | |
288 if (response_code != net::HTTP_OK) { | |
289 DLOG(WARNING) << "Response code: " << response_code; | |
290 std::string response; | |
291 source->GetResponseAsString(&response); | |
292 DLOG(WARNING) << "Response: " << response; | |
293 Respond(base::nullopt); | |
294 return; | |
295 } | |
296 | |
297 std::string response; | |
298 bool success = source->GetResponseAsString(&response); | |
299 DCHECK(success); | |
300 | |
301 // The response may start with )]}'. Ignore this. | |
302 base::StringPiece response_sp(response); | |
303 if (response_sp.starts_with(kResponsePreamble)) | |
304 response_sp.remove_prefix(strlen(kResponsePreamble)); | |
305 | |
306 int error_code = 0; | |
307 std::string error_msg; | |
308 std::unique_ptr<const base::Value> value = | |
309 base::JSONReader::ReadAndReturnError(response_sp, | |
sfiera
2017/04/13 09:42:51
Sorry, but… safe_json?
Marc Treib
2017/04/13 10:23:53
Hm, not sure if that's required here: We're gettin
sfiera
2017/04/13 10:38:38
That has been true of all the other cases I know t
Marc Treib
2017/04/13 12:06:59
It was not true in the original case that triggere
| |
310 base::JSON_ALLOW_TRAILING_COMMAS, | |
311 &error_code, &error_msg); | |
312 if (!value) { | |
sfiera
2017/04/13 09:42:51
Would be nice to have the remainder of the functio
Marc Treib
2017/04/13 10:23:53
Good idea! Done.
| |
313 DLOG(WARNING) << error_code << ": " << error_msg; | |
314 Respond(base::nullopt); | |
315 return; | |
316 } | |
317 const base::DictionaryValue* dict = nullptr; | |
318 if (!value->GetAsDictionary(&dict)) { | |
319 DLOG(WARNING) << "Parse error: top-level dictionary not found"; | |
320 Respond(base::nullopt); | |
321 return; | |
322 } | |
323 | |
324 const base::DictionaryValue* one_google_bar = nullptr; | |
325 if (!dict->GetDictionary("oneGoogleBar", &one_google_bar)) { | |
326 DLOG(WARNING) << "Parse error: no oneGoogleBar"; | |
327 Respond(base::nullopt); | |
328 return; | |
329 } | |
330 | |
331 OneGoogleBarData result; | |
332 | |
333 if (!safe_html::GetHtml(*one_google_bar, "html", &result.bar_html)) { | |
334 DLOG(WARNING) << "Parse error: no html"; | |
335 Respond(base::nullopt); | |
336 return; | |
337 } | |
338 | |
339 const base::DictionaryValue* page_hooks = nullptr; | |
340 if (!one_google_bar->GetDictionary("pageHooks", &page_hooks)) { | |
341 DLOG(WARNING) << "Parse error: no pageHooks"; | |
342 Respond(base::nullopt); | |
343 return; | |
344 } | |
345 | |
346 safe_html::GetScript(*page_hooks, "inHeadScript", &result.in_head_script); | |
347 safe_html::GetStyleSheet(*page_hooks, "inHeadStyle", &result.in_head_style); | |
348 safe_html::GetScript(*page_hooks, "afterBarScript", &result.after_bar_script); | |
349 safe_html::GetHtml(*page_hooks, "endOfBodyHtml", &result.end_of_body_html); | |
350 safe_html::GetScript(*page_hooks, "endOfBodyScript", | |
351 &result.end_of_body_script); | |
352 | |
353 Respond(result); | |
sfiera
2017/04/13 09:42:51
This is going to make a copy of |result| to create
Marc Treib
2017/04/13 10:23:53
I think so, yes. I've made OneGoogleBarData movabl
sfiera
2017/04/13 10:38:38
Yep, looks good.
| |
354 } | |
355 | |
356 void OneGoogleBarFetcherImpl::Respond( | |
357 const base::Optional<OneGoogleBarData>& data) { | |
358 for (auto& callback : callbacks_) { | |
359 std::move(callback).Run(data); | |
360 } | |
361 callbacks_.clear(); | |
362 } | |
OLD | NEW |