Local NTP: Introduce OneGoogleBarFetcher

BUG=583292

Review-Url: https://codereview.chromium.org/2814753002
Cr-Commit-Position: refs/heads/master@{#464393}
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn
index 97f28975..ab942d6 100644
--- a/chrome/browser/BUILD.gn
+++ b/chrome/browser/BUILD.gn
@@ -3483,6 +3483,11 @@
       "repost_form_warning_controller.h",
       "search/local_ntp_source.cc",
       "search/local_ntp_source.h",
+      "search/one_google_bar/one_google_bar_data.cc",
+      "search/one_google_bar/one_google_bar_data.h",
+      "search/one_google_bar/one_google_bar_fetcher.h",
+      "search/one_google_bar/one_google_bar_fetcher_impl.cc",
+      "search/one_google_bar/one_google_bar_fetcher_impl.h",
       "signin/signin_promo.cc",
       "signin/signin_promo.h",
       "signin/signin_ui_util.cc",
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_data.cc b/chrome/browser/search/one_google_bar/one_google_bar_data.cc
new file mode 100644
index 0000000..eac69e8
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_data.cc
@@ -0,0 +1,14 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/search/one_google_bar/one_google_bar_data.h"
+
+OneGoogleBarData::OneGoogleBarData() = default;
+OneGoogleBarData::OneGoogleBarData(const OneGoogleBarData&) = default;
+OneGoogleBarData::OneGoogleBarData(OneGoogleBarData&&) = default;
+OneGoogleBarData::~OneGoogleBarData() = default;
+
+OneGoogleBarData& OneGoogleBarData::operator=(const OneGoogleBarData&) =
+    default;
+OneGoogleBarData& OneGoogleBarData::operator=(OneGoogleBarData&&) = default;
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_data.h b/chrome/browser/search/one_google_bar/one_google_bar_data.h
new file mode 100644
index 0000000..caf3a27
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_data.h
@@ -0,0 +1,32 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_DATA_H_
+#define CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_DATA_H_
+
+#include <string>
+
+// This struct contains all the data needed to inject a OneGoogleBar into a
+// page.
+struct OneGoogleBarData {
+  OneGoogleBarData();
+  OneGoogleBarData(const OneGoogleBarData&);
+  OneGoogleBarData(OneGoogleBarData&&);
+  ~OneGoogleBarData();
+
+  OneGoogleBarData& operator=(const OneGoogleBarData&);
+  OneGoogleBarData& operator=(OneGoogleBarData&&);
+
+  // The main HTML for the bar itself.
+  std::string bar_html;
+
+  // "Page hooks" that need to be inserted at certain points in the page HTML.
+  std::string in_head_script;
+  std::string in_head_style;
+  std::string after_bar_script;
+  std::string end_of_body_html;
+  std::string end_of_body_script;
+};
+
+#endif  // CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_DATA_H_
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h b/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h
new file mode 100644
index 0000000..4b42d421
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h
@@ -0,0 +1,24 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_H_
+#define CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_H_
+
+#include "base/callback_forward.h"
+#include "base/optional.h"
+
+struct OneGoogleBarData;
+
+// Interface for fetching OneGoogleBarData over the network.
+class OneGoogleBarFetcher {
+ public:
+  using OneGoogleCallback =
+      base::OnceCallback<void(const base::Optional<OneGoogleBarData>&)>;
+
+  // Initiates a fetch from the network. On completion (successful or not), the
+  // callback will be called with the result, which will be nullopt on failure.
+  virtual void Fetch(OneGoogleCallback callback) = 0;
+};
+
+#endif  // CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_H_
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc
new file mode 100644
index 0000000..704f878
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc
@@ -0,0 +1,374 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h"
+
+#include <string>
+#include <utility>
+
+#include "base/callback.h"
+#include "base/command_line.h"
+#include "base/json/json_writer.h"
+#include "base/memory/ptr_util.h"
+#include "base/strings/string_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/values.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/search/one_google_bar/one_google_bar_data.h"
+#include "chrome/common/chrome_content_client.h"
+#include "components/google/core/browser/google_url_tracker.h"
+#include "components/safe_json/safe_json_parser.h"
+#include "components/signin/core/browser/access_token_fetcher.h"
+#include "components/signin/core/browser/signin_manager.h"
+#include "components/variations/net/variations_http_headers.h"
+#include "google_apis/gaia/oauth2_token_service.h"
+#include "google_apis/google_api_keys.h"
+#include "net/base/load_flags.h"
+#include "net/http/http_status_code.h"
+#include "net/url_request/url_fetcher.h"
+#include "net/url_request/url_fetcher_delegate.h"
+
+namespace {
+
+const char kApiUrl[] = "https://onegoogle-pa.googleapis.com/v1/getbar";
+
+const char kApiKeyFormat[] = "?key=%s";
+
+const char kApiScope[] = "https://www.googleapis.com/auth/onegoogle.readonly";
+const char kAuthorizationRequestHeaderFormat[] = "Bearer %s";
+
+const char kResponsePreamble[] = ")]}'";
+
+// This namespace contains helpers to extract SafeHtml-wrapped strings (see
+// https://github.com/google/safe-html-types) from the response json. If there
+// is ever a C++ version of the SafeHtml types, we should consider using that
+// instead of these custom functions.
+namespace safe_html {
+
+bool GetImpl(const base::DictionaryValue& dict,
+             const std::string& name,
+             const std::string& wrapped_field_name,
+             std::string* out) {
+  const base::DictionaryValue* value = nullptr;
+  if (!dict.GetDictionary(name, &value)) {
+    out->clear();
+    return false;
+  }
+
+  if (!value->GetString(wrapped_field_name, out)) {
+    out->clear();
+    return false;
+  }
+
+  return true;
+}
+
+bool GetHtml(const base::DictionaryValue& dict,
+             const std::string& name,
+             std::string* out) {
+  return GetImpl(dict, name, "privateDoNotAccessOrElseSafeHtmlWrappedValue",
+                 out);
+}
+
+bool GetScript(const base::DictionaryValue& dict,
+               const std::string& name,
+               std::string* out) {
+  return GetImpl(dict, name, "privateDoNotAccessOrElseSafeScriptWrappedValue",
+                 out);
+}
+
+bool GetStyleSheet(const base::DictionaryValue& dict,
+                   const std::string& name,
+                   std::string* out) {
+  return GetImpl(dict, name,
+                 "privateDoNotAccessOrElseSafeStyleSheetWrappedValue", out);
+}
+
+}  // namespace safe_html
+
+base::Optional<OneGoogleBarData> JsonToOGBData(const base::Value& value) {
+  const base::DictionaryValue* dict = nullptr;
+  if (!value.GetAsDictionary(&dict)) {
+    DLOG(WARNING) << "Parse error: top-level dictionary not found";
+    return base::nullopt;
+  }
+
+  const base::DictionaryValue* one_google_bar = nullptr;
+  if (!dict->GetDictionary("oneGoogleBar", &one_google_bar)) {
+    DLOG(WARNING) << "Parse error: no oneGoogleBar";
+    return base::nullopt;
+  }
+
+  OneGoogleBarData result;
+
+  if (!safe_html::GetHtml(*one_google_bar, "html", &result.bar_html)) {
+    DLOG(WARNING) << "Parse error: no html";
+    return base::nullopt;
+  }
+
+  const base::DictionaryValue* page_hooks = nullptr;
+  if (!one_google_bar->GetDictionary("pageHooks", &page_hooks)) {
+    DLOG(WARNING) << "Parse error: no pageHooks";
+    return base::nullopt;
+  }
+
+  safe_html::GetScript(*page_hooks, "inHeadScript", &result.in_head_script);
+  safe_html::GetStyleSheet(*page_hooks, "inHeadStyle", &result.in_head_style);
+  safe_html::GetScript(*page_hooks, "afterBarScript", &result.after_bar_script);
+  safe_html::GetHtml(*page_hooks, "endOfBodyHtml", &result.end_of_body_html);
+  safe_html::GetScript(*page_hooks, "endOfBodyScript",
+                       &result.end_of_body_script);
+
+  return result;
+}
+
+}  // namespace
+
+class OneGoogleBarFetcherImpl::AuthenticatedURLFetcher
+    : public net::URLFetcherDelegate {
+ public:
+  using FetchDoneCallback = base::OnceCallback<void(const net::URLFetcher*)>;
+
+  AuthenticatedURLFetcher(SigninManagerBase* signin_manager,
+                          OAuth2TokenService* token_service,
+                          net::URLRequestContextGetter* request_context,
+                          const GURL& google_base_url,
+                          FetchDoneCallback callback);
+  ~AuthenticatedURLFetcher() override = default;
+
+  void Start();
+
+ private:
+  GURL GetApiUrl(bool use_oauth) const;
+  std::string GetRequestBody() const;
+  std::string GetExtraRequestHeaders(const GURL& url,
+                                     const std::string& access_token) const;
+
+  void GotAccessToken(const GoogleServiceAuthError& error,
+                      const std::string& access_token);
+
+  // URLFetcherDelegate implementation.
+  void OnURLFetchComplete(const net::URLFetcher* source) override;
+
+  SigninManagerBase* const signin_manager_;
+  OAuth2TokenService* const token_service_;
+  net::URLRequestContextGetter* const request_context_;
+  const GURL google_base_url_;
+
+  FetchDoneCallback callback_;
+
+  std::unique_ptr<AccessTokenFetcher> token_fetcher_;
+
+  // The underlying URLFetcher which does the actual fetch.
+  std::unique_ptr<net::URLFetcher> url_fetcher_;
+};
+
+OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::AuthenticatedURLFetcher(
+    SigninManagerBase* signin_manager,
+    OAuth2TokenService* token_service,
+    net::URLRequestContextGetter* request_context,
+    const GURL& google_base_url,
+    FetchDoneCallback callback)
+    : signin_manager_(signin_manager),
+      token_service_(token_service),
+      request_context_(request_context),
+      google_base_url_(google_base_url),
+      callback_(std::move(callback)) {}
+
+void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::Start() {
+  if (!signin_manager_->IsAuthenticated()) {
+    GotAccessToken(GoogleServiceAuthError::AuthErrorNone(), std::string());
+    return;
+  }
+  OAuth2TokenService::ScopeSet scopes;
+  scopes.insert(kApiScope);
+  token_fetcher_ = base::MakeUnique<AccessTokenFetcher>(
+      "one_google", signin_manager_, token_service_, scopes,
+      base::BindOnce(&AuthenticatedURLFetcher::GotAccessToken,
+                     base::Unretained(this)));
+}
+
+GURL OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetApiUrl(
+    bool use_oauth) const {
+  std::string api_url(kApiUrl);
+  // TODO(treib): Attach to feature instead of cmdline.
+  base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
+  if (cmdline->HasSwitch("one-google-api-url"))
+    api_url = cmdline->GetSwitchValueASCII("one-google-api-url");
+  // Append the API key only for unauthenticated requests.
+  if (!use_oauth) {
+    api_url +=
+        base::StringPrintf(kApiKeyFormat, google_apis::GetAPIKey().c_str());
+  }
+
+  return GURL(api_url);
+}
+
+std::string OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetRequestBody()
+    const {
+  // TODO(treib): Attach to feature instead of cmdline.
+  base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
+  if (cmdline->HasSwitch("one-google-bar-options"))
+    return cmdline->GetSwitchValueASCII("one-google-bar-options");
+
+  base::DictionaryValue dict;
+  dict.SetInteger("subproduct", 243);
+  dict.SetBoolean("enable_multilogin", true);
+  dict.SetString("user_agent", GetUserAgent());
+  dict.SetString("accept_language", g_browser_process->GetApplicationLocale());
+  dict.SetString("original_request_url", google_base_url_.spec());
+  auto material_options_dict = base::MakeUnique<base::DictionaryValue>();
+  material_options_dict->SetString("page_title", " ");
+  material_options_dict->SetBoolean("position_fixed", true);
+  material_options_dict->SetBoolean("disable_moving_userpanel_to_menu", true);
+  auto styling_options_dict = base::MakeUnique<base::DictionaryValue>();
+  auto background_color_dict = base::MakeUnique<base::DictionaryValue>();
+  auto alpha_dict = base::MakeUnique<base::DictionaryValue>();
+  alpha_dict->SetInteger("value", 0);
+  background_color_dict->Set("alpha", std::move(alpha_dict));
+  styling_options_dict->Set("background_color",
+                            std::move(background_color_dict));
+  material_options_dict->Set("styling_options",
+                             std::move(styling_options_dict));
+  dict.Set("material_options", std::move(material_options_dict));
+
+  std::string result;
+  base::JSONWriter::Write(dict, &result);
+  return result;
+}
+
+std::string
+OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetExtraRequestHeaders(
+    const GURL& url,
+    const std::string& access_token) const {
+  net::HttpRequestHeaders headers;
+  headers.SetHeader("Content-Type", "application/json; charset=UTF-8");
+  if (!access_token.empty()) {
+    headers.SetHeader("Authorization",
+                      base::StringPrintf(kAuthorizationRequestHeaderFormat,
+                                         access_token.c_str()));
+  }
+  // Note: It's OK to pass |is_signed_in| false if it's unknown, as it does
+  // not affect transmission of experiments coming from the variations server.
+  variations::AppendVariationHeaders(url,
+                                     /*incognito=*/false, /*uma_enabled=*/false,
+                                     /*is_signed_in=*/false, &headers);
+  return headers.ToString();
+}
+
+void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GotAccessToken(
+    const GoogleServiceAuthError& error,
+    const std::string& access_token) {
+  // Delete the token fetcher after we leave this method.
+  std::unique_ptr<AccessTokenFetcher> deleter(std::move(token_fetcher_));
+
+  bool use_oauth = !access_token.empty();
+  GURL url = GetApiUrl(use_oauth);
+  url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::POST, this);
+  url_fetcher_->SetRequestContext(request_context_);
+
+  url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_AUTH_DATA |
+                             net::LOAD_DO_NOT_SEND_COOKIES |
+                             net::LOAD_DO_NOT_SAVE_COOKIES);
+  url_fetcher_->SetUploadData("application/json", GetRequestBody());
+  url_fetcher_->SetExtraRequestHeaders(
+      GetExtraRequestHeaders(url, access_token));
+
+  url_fetcher_->Start();
+}
+
+void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::OnURLFetchComplete(
+    const net::URLFetcher* source) {
+  std::move(callback_).Run(source);
+}
+
+OneGoogleBarFetcherImpl::OneGoogleBarFetcherImpl(
+    SigninManagerBase* signin_manager,
+    OAuth2TokenService* token_service,
+    net::URLRequestContextGetter* request_context,
+    GoogleURLTracker* google_url_tracker)
+    : signin_manager_(signin_manager),
+      token_service_(token_service),
+      request_context_(request_context),
+      google_url_tracker_(google_url_tracker),
+      weak_ptr_factory_(this) {}
+
+OneGoogleBarFetcherImpl::~OneGoogleBarFetcherImpl() = default;
+
+void OneGoogleBarFetcherImpl::Fetch(OneGoogleCallback callback) {
+  callbacks_.push_back(std::move(callback));
+  IssueRequestIfNoneOngoing();
+}
+
+void OneGoogleBarFetcherImpl::IssueRequestIfNoneOngoing() {
+  // If there is an ongoing request, let it complete.
+  if (pending_request_.get())
+    return;
+
+  pending_request_ = base::MakeUnique<AuthenticatedURLFetcher>(
+      signin_manager_, token_service_, request_context_,
+      google_url_tracker_->google_url(),
+      base::BindOnce(&OneGoogleBarFetcherImpl::FetchDone,
+                     base::Unretained(this)));
+  pending_request_->Start();
+}
+
+void OneGoogleBarFetcherImpl::FetchDone(const net::URLFetcher* source) {
+  // The fetcher will be deleted when the request is handled.
+  std::unique_ptr<AuthenticatedURLFetcher> deleter(std::move(pending_request_));
+
+  const net::URLRequestStatus& request_status = source->GetStatus();
+  if (request_status.status() != net::URLRequestStatus::SUCCESS) {
+    // This represents network errors (i.e. the server did not provide a
+    // response).
+    DLOG(WARNING) << "Request failed with error: " << request_status.error()
+                  << ": " << net::ErrorToString(request_status.error());
+    Respond(base::nullopt);
+    return;
+  }
+
+  const int response_code = source->GetResponseCode();
+  if (response_code != net::HTTP_OK) {
+    DLOG(WARNING) << "Response code: " << response_code;
+    std::string response;
+    source->GetResponseAsString(&response);
+    DLOG(WARNING) << "Response: " << response;
+    Respond(base::nullopt);
+    return;
+  }
+
+  std::string response;
+  bool success = source->GetResponseAsString(&response);
+  DCHECK(success);
+
+  // The response may start with )]}'. Ignore this.
+  if (base::StartsWith(response, kResponsePreamble,
+                       base::CompareCase::SENSITIVE)) {
+    response = response.substr(strlen(kResponsePreamble));
+  }
+
+  safe_json::SafeJsonParser::Parse(
+      response,
+      base::Bind(&OneGoogleBarFetcherImpl::JsonParsed,
+                 weak_ptr_factory_.GetWeakPtr()),
+      base::Bind(&OneGoogleBarFetcherImpl::JsonParseFailed,
+                 weak_ptr_factory_.GetWeakPtr()));
+}
+
+void OneGoogleBarFetcherImpl::JsonParsed(std::unique_ptr<base::Value> value) {
+  Respond(JsonToOGBData(*value));
+}
+
+void OneGoogleBarFetcherImpl::JsonParseFailed(const std::string& message) {
+  DLOG(WARNING) << "Parsing JSON failed: " << message;
+  Respond(base::nullopt);
+}
+
+void OneGoogleBarFetcherImpl::Respond(
+    const base::Optional<OneGoogleBarData>& data) {
+  for (auto& callback : callbacks_) {
+    std::move(callback).Run(data);
+  }
+  callbacks_.clear();
+}
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h
new file mode 100644
index 0000000..40538ef
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h
@@ -0,0 +1,67 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_IMPL_H_
+#define CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_IMPL_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/memory/weak_ptr.h"
+#include "base/optional.h"
+#include "chrome/browser/search/one_google_bar/one_google_bar_fetcher.h"
+
+class GoogleURLTracker;
+class OAuth2TokenService;
+class SigninManagerBase;
+
+namespace base {
+class Value;
+}
+
+namespace net {
+class URLFetcher;
+class URLRequestContextGetter;
+}  // namespace net
+
+struct OneGoogleBarData;
+
+class OneGoogleBarFetcherImpl : public OneGoogleBarFetcher {
+ public:
+  OneGoogleBarFetcherImpl(SigninManagerBase* signin_manager,
+                          OAuth2TokenService* token_service,
+                          net::URLRequestContextGetter* request_context,
+                          GoogleURLTracker* google_url_tracker);
+  ~OneGoogleBarFetcherImpl();
+
+  void Fetch(OneGoogleCallback callback) override;
+
+ private:
+  class AuthenticatedURLFetcher;
+
+  void IssueRequestIfNoneOngoing();
+
+  void FetchDone(const net::URLFetcher* source);
+
+  void JsonParsed(std::unique_ptr<base::Value> value);
+  void JsonParseFailed(const std::string& message);
+
+  void Respond(const base::Optional<OneGoogleBarData>& data);
+
+  SigninManagerBase* signin_manager_;
+  OAuth2TokenService* token_service_;
+  net::URLRequestContextGetter* request_context_;
+  GoogleURLTracker* google_url_tracker_;
+
+  std::vector<OneGoogleCallback> callbacks_;
+  std::unique_ptr<AuthenticatedURLFetcher> pending_request_;
+
+  base::WeakPtrFactory<OneGoogleBarFetcherImpl> weak_ptr_factory_;
+
+  DISALLOW_COPY_AND_ASSIGN(OneGoogleBarFetcherImpl);
+};
+
+#endif  // CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_IMPL_H_
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl_unittest.cc b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl_unittest.cc
new file mode 100644
index 0000000..7e05f845
--- /dev/null
+++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl_unittest.cc
@@ -0,0 +1,291 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h"
+
+#include "base/macros.h"
+#include "base/memory/ptr_util.h"
+#include "base/memory/ref_counted.h"
+#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
+#include "base/test/mock_callback.h"
+#include "base/test/test_simple_task_runner.h"
+#include "base/time/time.h"
+#include "chrome/browser/search/one_google_bar/one_google_bar_data.h"
+#include "components/google/core/browser/google_url_tracker.h"
+#include "components/safe_json/testing_json_parser.h"
+#include "components/signin/core/browser/account_tracker_service.h"
+#include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
+#include "components/signin/core/browser/fake_signin_manager.h"
+#include "components/signin/core/browser/test_signin_client.h"
+#include "components/sync_preferences/testing_pref_service_syncable.h"
+#include "google_apis/gaia/fake_oauth2_token_service_delegate.h"
+#include "net/http/http_request_headers.h"
+#include "net/http/http_status_code.h"
+#include "net/url_request/test_url_fetcher_factory.h"
+#include "net/url_request/url_request_status.h"
+#include "net/url_request/url_request_test_util.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+using testing::_;
+using testing::Eq;
+using testing::IsEmpty;
+using testing::SaveArg;
+using testing::StartsWith;
+
+namespace {
+
+const char kMinimalValidResponse[] = R"json({"oneGoogleBar": {
+  "html": { "privateDoNotAccessOrElseSafeHtmlWrappedValue": "" },
+  "pageHooks": {}
+}})json";
+
+// Required to instantiate a GoogleUrlTracker in UNIT_TEST_MODE.
+class GoogleURLTrackerClientStub : public GoogleURLTrackerClient {
+ public:
+  GoogleURLTrackerClientStub() {}
+  ~GoogleURLTrackerClientStub() override {}
+
+  bool IsBackgroundNetworkingEnabled() override { return true; }
+  PrefService* GetPrefs() override { return nullptr; }
+  net::URLRequestContextGetter* GetRequestContext() override { return nullptr; }
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClientStub);
+};
+
+}  // namespace
+
+class OneGoogleBarFetcherImplTest : public testing::Test {
+ public:
+  OneGoogleBarFetcherImplTest()
+      : signin_client_(&pref_service_),
+        signin_manager_(&signin_client_, &account_tracker_),
+        task_runner_(new base::TestSimpleTaskRunner()),
+        request_context_getter_(
+            new net::TestURLRequestContextGetter(task_runner_)),
+        token_service_(base::MakeUnique<FakeOAuth2TokenServiceDelegate>(
+            request_context_getter_.get())),
+        google_url_tracker_(base::MakeUnique<GoogleURLTrackerClientStub>(),
+                            GoogleURLTracker::UNIT_TEST_MODE),
+        one_google_bar_fetcher_(&signin_manager_,
+                                &token_service_,
+                                request_context_getter_.get(),
+                                &google_url_tracker_) {
+    SigninManagerBase::RegisterProfilePrefs(pref_service_.registry());
+    SigninManagerBase::RegisterPrefs(pref_service_.registry());
+  }
+
+  void SignIn() {
+    signin_manager_.SignIn("account");
+    token_service_.GetDelegate()->UpdateCredentials("account", "refresh_token");
+  }
+
+  void IssueAccessToken() {
+    token_service_.IssueAllTokensForAccount(
+        "account", "access_token",
+        base::Time::Now() + base::TimeDelta::FromHours(1));
+  }
+
+  void IssueAccessTokenError() {
+    token_service_.IssueErrorForAllPendingRequestsForAccount(
+        "account",
+        GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE));
+  }
+
+  net::TestURLFetcher* GetRunningURLFetcher() {
+    // All created URLFetchers have ID 0 by default.
+    net::TestURLFetcher* url_fetcher = url_fetcher_factory_.GetFetcherByID(0);
+    DCHECK(url_fetcher);
+    return url_fetcher;
+  }
+
+  void RespondWithData(const std::string& data) {
+    net::TestURLFetcher* url_fetcher = GetRunningURLFetcher();
+    url_fetcher->set_status(net::URLRequestStatus());
+    url_fetcher->set_response_code(net::HTTP_OK);
+    url_fetcher->SetResponseString(data);
+    url_fetcher->delegate()->OnURLFetchComplete(url_fetcher);
+    // SafeJsonParser is asynchronous.
+    base::RunLoop().RunUntilIdle();
+  }
+
+  OneGoogleBarFetcherImpl* one_google_bar_fetcher() {
+    return &one_google_bar_fetcher_;
+  }
+
+ private:
+  // variations::AppendVariationHeaders and SafeJsonParser require a
+  // ThreadTaskRunnerHandle to be set.
+  base::MessageLoop message_loop_;
+
+  safe_json::TestingJsonParser::ScopedFactoryOverride factory_override_;
+
+  net::TestURLFetcherFactory url_fetcher_factory_;
+  sync_preferences::TestingPrefServiceSyncable pref_service_;
+
+  TestSigninClient signin_client_;
+  AccountTrackerService account_tracker_;
+  FakeSigninManagerBase signin_manager_;
+
+  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
+  scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
+  FakeProfileOAuth2TokenService token_service_;
+  GoogleURLTracker google_url_tracker_;
+
+  OneGoogleBarFetcherImpl one_google_bar_fetcher_;
+};
+
+TEST_F(OneGoogleBarFetcherImplTest, UnauthenticatedRequestReturns) {
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  base::Optional<OneGoogleBarData> data;
+  EXPECT_CALL(callback, Run(_)).WillOnce(SaveArg<0>(&data));
+  RespondWithData(kMinimalValidResponse);
+
+  EXPECT_TRUE(data.has_value());
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, AuthenticatedRequestReturns) {
+  SignIn();
+
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  IssueAccessToken();
+
+  base::Optional<OneGoogleBarData> data;
+  EXPECT_CALL(callback, Run(_)).WillOnce(SaveArg<0>(&data));
+  RespondWithData(kMinimalValidResponse);
+
+  EXPECT_TRUE(data.has_value());
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, UnauthenticatedRequestHasApiKey) {
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  // The request should have an API key (as a query param).
+  EXPECT_THAT(GetRunningURLFetcher()->GetOriginalURL().query(),
+              StartsWith("key="));
+
+  // But no "Authorization" header.
+  net::HttpRequestHeaders headers;
+  GetRunningURLFetcher()->GetExtraRequestHeaders(&headers);
+  EXPECT_FALSE(headers.HasHeader("Authorization"));
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, AuthenticatedRequestHasAuthHeader) {
+  SignIn();
+
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  IssueAccessToken();
+
+  // The request should *not* have an API key (as a query param).
+  EXPECT_THAT(GetRunningURLFetcher()->GetOriginalURL().query(), IsEmpty());
+
+  // It should have an "Authorization" header.
+  net::HttpRequestHeaders headers;
+  GetRunningURLFetcher()->GetExtraRequestHeaders(&headers);
+  EXPECT_TRUE(headers.HasHeader("Authorization"));
+}
+
+TEST_F(OneGoogleBarFetcherImplTest,
+       AuthenticatedRequestFallsBackToUnauthenticated) {
+  SignIn();
+
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  IssueAccessTokenError();
+
+  // The request should have fallen back to unauthenticated mode with an API key
+  // (as a query param).
+  EXPECT_THAT(GetRunningURLFetcher()->GetOriginalURL().query(),
+              StartsWith("key="));
+
+  // But no "Authorization" header.
+  net::HttpRequestHeaders headers;
+  GetRunningURLFetcher()->GetExtraRequestHeaders(&headers);
+  EXPECT_FALSE(headers.HasHeader("Authorization"));
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, HandlesResponsePreamble) {
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  // The reponse may contain a ")]}'" prefix. The fetcher should ignore that
+  // during parsing.
+  base::Optional<OneGoogleBarData> data;
+  EXPECT_CALL(callback, Run(_)).WillOnce(SaveArg<0>(&data));
+  RespondWithData(std::string(")]}'") + kMinimalValidResponse);
+
+  EXPECT_TRUE(data.has_value());
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, ParsesFullResponse) {
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> callback;
+  one_google_bar_fetcher()->Fetch(callback.Get());
+
+  base::Optional<OneGoogleBarData> data;
+  EXPECT_CALL(callback, Run(_)).WillOnce(SaveArg<0>(&data));
+  RespondWithData(R"json({"oneGoogleBar": {
+    "html": { "privateDoNotAccessOrElseSafeHtmlWrappedValue": "bar_html" },
+    "pageHooks": {
+      "inHeadScript": {
+        "privateDoNotAccessOrElseSafeScriptWrappedValue": "in_head_script"
+      },
+      "inHeadStyle": {
+        "privateDoNotAccessOrElseSafeStyleSheetWrappedValue": "in_head_style"
+      },
+      "afterBarScript": {
+        "privateDoNotAccessOrElseSafeScriptWrappedValue": "after_bar_script"
+      },
+      "endOfBodyHtml": {
+        "privateDoNotAccessOrElseSafeHtmlWrappedValue": "end_of_body_html"
+      },
+      "endOfBodyScript": {
+        "privateDoNotAccessOrElseSafeScriptWrappedValue": "end_of_body_script"
+      }
+    }
+  }})json");
+
+  ASSERT_TRUE(data.has_value());
+  EXPECT_THAT(data->bar_html, Eq("bar_html"));
+  EXPECT_THAT(data->in_head_script, Eq("in_head_script"));
+  EXPECT_THAT(data->in_head_style, Eq("in_head_style"));
+  EXPECT_THAT(data->after_bar_script, Eq("after_bar_script"));
+  EXPECT_THAT(data->end_of_body_html, Eq("end_of_body_html"));
+  EXPECT_THAT(data->end_of_body_script, Eq("end_of_body_script"));
+}
+
+TEST_F(OneGoogleBarFetcherImplTest, CoalescesMultipleRequests) {
+  // Trigger two requests.
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> first_callback;
+  one_google_bar_fetcher()->Fetch(first_callback.Get());
+  net::URLFetcher* first_fetcher = GetRunningURLFetcher();
+  base::MockCallback<OneGoogleBarFetcher::OneGoogleCallback> second_callback;
+  one_google_bar_fetcher()->Fetch(second_callback.Get());
+  net::URLFetcher* second_fetcher = GetRunningURLFetcher();
+
+  // Expect that only one fetcher handles both requests.
+  EXPECT_THAT(first_fetcher, Eq(second_fetcher));
+
+  // But both callbacks should get called.
+  base::Optional<OneGoogleBarData> first_data;
+  base::Optional<OneGoogleBarData> second_data;
+
+  EXPECT_CALL(first_callback, Run(_)).WillOnce(SaveArg<0>(&first_data));
+  EXPECT_CALL(second_callback, Run(_)).WillOnce(SaveArg<0>(&second_data));
+
+  RespondWithData(kMinimalValidResponse);
+
+  // Ensure that both requests received a response.
+  EXPECT_TRUE(first_data.has_value());
+  EXPECT_TRUE(second_data.has_value());
+}
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn
index 80abde9b..0448b032 100644
--- a/chrome/test/BUILD.gn
+++ b/chrome/test/BUILD.gn
@@ -3671,6 +3671,7 @@
       "../browser/search/instant_service_unittest.cc",
       "../browser/search/instant_unittest_base.cc",
       "../browser/search/instant_unittest_base.h",
+      "../browser/search/one_google_bar/one_google_bar_fetcher_impl_unittest.cc",
       "../browser/search/search_unittest.cc",
       "../browser/sessions/persistent_tab_restore_service_unittest.cc",
       "../browser/signin/mutable_profile_oauth2_token_service_delegate_unittest.cc",