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