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