headless_browser_context_browsertest.cc 9.74 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 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 <memory>

altimin's avatar
altimin committed
7
#include "base/files/scoped_temp_dir.h"
8 9
#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
altimin's avatar
altimin committed
10
#include "base/threading/thread_restrictions.h"
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "content/public/test/browser_test.h"
#include "headless/public/domains/runtime.h"
#include "headless/public/headless_browser.h"
#include "headless/public/headless_browser_context.h"
#include "headless/public/headless_devtools_client.h"
#include "headless/public/headless_devtools_target.h"
#include "headless/public/headless_web_contents.h"
#include "headless/test/headless_browser_test.h"
#include "headless/test/test_protocol_handler.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/url_request/url_request_job.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/size.h"

namespace headless {
namespace {
const char kMainPageCookie[] = "mood=quizzical";
const char kIsolatedPageCookie[] = "mood=quixotic";
}  // namespace

// This test creates two tabs pointing to the same security origin in two
// different browser contexts and checks that they are isolated by creating two
// cookies with the same name in both tabs. The steps are:
//
// 1. Wait for tab #1 to become ready for DevTools.
// 2. Create tab #2 and wait for it to become ready for DevTools.
// 3. Navigate tab #1 to the test page and wait for it to finish loading.
// 4. Navigate tab #2 to the test page and wait for it to finish loading.
// 5. Set a cookie in tab #1.
// 6. Set the same cookie in tab #2 to a different value.
// 7. Read the cookie in tab #1 and check that it has the first value.
// 8. Read the cookie in tab #2 and check that it has the second value.
//
// If the tabs aren't properly isolated, step 7 will fail.
class HeadlessBrowserContextIsolationTest
    : public HeadlessAsyncDevTooledBrowserTest {
 public:
  HeadlessBrowserContextIsolationTest()
51 52
      : browser_context_(nullptr),
        web_contents2_(nullptr),
53 54 55 56 57 58 59 60
        devtools_client2_(HeadlessDevToolsClient::Create()) {
    EXPECT_TRUE(embedded_test_server()->Start());
  }

  // HeadlessWebContentsObserver implementation:
  void DevToolsTargetReady() override {
    if (!web_contents2_) {
      browser_context_ = browser()->CreateBrowserContextBuilder().Build();
altimin's avatar
altimin committed
61
      web_contents2_ = browser_context_->CreateWebContentsBuilder().Build();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      web_contents2_->AddObserver(this);
      return;
    }

    web_contents2_->GetDevToolsTarget()->AttachClient(devtools_client2_.get());
    HeadlessAsyncDevTooledBrowserTest::DevToolsTargetReady();
  }

  void RunDevTooledTest() override {
    load_observer_.reset(new LoadObserver(
        devtools_client_.get(),
        base::Bind(&HeadlessBrowserContextIsolationTest::OnFirstLoadComplete,
                   base::Unretained(this))));
    devtools_client_->GetPage()->Navigate(
        embedded_test_server()->GetURL("/hello.html").spec());
  }

  void OnFirstLoadComplete() {
    EXPECT_TRUE(load_observer_->navigation_succeeded());
    load_observer_.reset(new LoadObserver(
        devtools_client2_.get(),
        base::Bind(&HeadlessBrowserContextIsolationTest::OnSecondLoadComplete,
                   base::Unretained(this))));
    devtools_client2_->GetPage()->Navigate(
        embedded_test_server()->GetURL("/hello.html").spec());
  }

  void OnSecondLoadComplete() {
    EXPECT_TRUE(load_observer_->navigation_succeeded());
    load_observer_.reset();

    devtools_client_->GetRuntime()->Evaluate(
        base::StringPrintf("document.cookie = '%s'", kMainPageCookie),
        base::Bind(&HeadlessBrowserContextIsolationTest::OnFirstSetCookieResult,
                   base::Unretained(this)));
  }

  void OnFirstSetCookieResult(std::unique_ptr<runtime::EvaluateResult> result) {
    std::string cookie;
    EXPECT_TRUE(result->GetResult()->GetValue()->GetAsString(&cookie));
    EXPECT_EQ(kMainPageCookie, cookie);

    devtools_client2_->GetRuntime()->Evaluate(
        base::StringPrintf("document.cookie = '%s'", kIsolatedPageCookie),
        base::Bind(
            &HeadlessBrowserContextIsolationTest::OnSecondSetCookieResult,
            base::Unretained(this)));
  }

  void OnSecondSetCookieResult(
      std::unique_ptr<runtime::EvaluateResult> result) {
    std::string cookie;
    EXPECT_TRUE(result->GetResult()->GetValue()->GetAsString(&cookie));
    EXPECT_EQ(kIsolatedPageCookie, cookie);

    devtools_client_->GetRuntime()->Evaluate(
        "document.cookie",
        base::Bind(&HeadlessBrowserContextIsolationTest::OnFirstGetCookieResult,
                   base::Unretained(this)));
  }

  void OnFirstGetCookieResult(std::unique_ptr<runtime::EvaluateResult> result) {
    std::string cookie;
    EXPECT_TRUE(result->GetResult()->GetValue()->GetAsString(&cookie));
    EXPECT_EQ(kMainPageCookie, cookie);

    devtools_client2_->GetRuntime()->Evaluate(
        "document.cookie",
        base::Bind(
            &HeadlessBrowserContextIsolationTest::OnSecondGetCookieResult,
            base::Unretained(this)));
  }

  void OnSecondGetCookieResult(
      std::unique_ptr<runtime::EvaluateResult> result) {
    std::string cookie;
    EXPECT_TRUE(result->GetResult()->GetValue()->GetAsString(&cookie));
    EXPECT_EQ(kIsolatedPageCookie, cookie);
    FinishTest();
  }

  void FinishTest() {
    web_contents2_->RemoveObserver(this);
    web_contents2_->Close();
146
    browser_context_->Close();
147 148 149 150
    FinishAsynchronousTest();
  }

 private:
151
  HeadlessBrowserContext* browser_context_;
152 153 154 155 156 157 158 159 160 161 162
  HeadlessWebContents* web_contents2_;
  std::unique_ptr<HeadlessDevToolsClient> devtools_client2_;
  std::unique_ptr<LoadObserver> load_observer_;
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessBrowserContextIsolationTest);

IN_PROC_BROWSER_TEST_F(HeadlessBrowserTest, ContextProtocolHandler) {
  const std::string kResponseBody = "<p>HTTP response body</p>";
  ProtocolHandlerMap protocol_handlers;
  protocol_handlers[url::kHttpScheme] =
163
      base::MakeUnique<TestProtocolHandler>(kResponseBody);
164 165 166

  // Load a page which doesn't actually exist, but which is fetched by our
  // custom protocol handler.
167
  HeadlessBrowserContext* browser_context =
168 169 170 171 172
      browser()
          ->CreateBrowserContextBuilder()
          .SetProtocolHandlers(std::move(protocol_handlers))
          .Build();
  HeadlessWebContents* web_contents =
altimin's avatar
altimin committed
173
      browser_context->CreateWebContentsBuilder()
174 175 176 177 178 179 180 181 182 183 184 185
          .SetInitialURL(GURL("http://not-an-actual-domain.tld/hello.html"))
          .Build();
  EXPECT_TRUE(WaitForLoad(web_contents));

  std::string inner_html;
  EXPECT_TRUE(EvaluateScript(web_contents, "document.body.innerHTML")
                  ->GetResult()
                  ->GetValue()
                  ->GetAsString(&inner_html));
  EXPECT_EQ(kResponseBody, inner_html);
  web_contents->Close();

186
  HeadlessBrowserContext* another_browser_context =
altimin's avatar
altimin committed
187 188 189
      browser()->CreateBrowserContextBuilder().Build();

  // Loading the same non-existent page using a tab with a different context
190 191 192
  // should not work since the protocol handler only exists on the custom
  // context.
  web_contents =
altimin's avatar
altimin committed
193
      another_browser_context->CreateWebContentsBuilder()
194 195 196 197 198 199 200 201 202 203 204
          .SetInitialURL(GURL("http://not-an-actual-domain.tld/hello.html"))
          .Build();
  EXPECT_TRUE(WaitForLoad(web_contents));
  EXPECT_TRUE(EvaluateScript(web_contents, "document.body.innerHTML")
                  ->GetResult()
                  ->GetValue()
                  ->GetAsString(&inner_html));
  EXPECT_EQ("", inner_html);
  web_contents->Close();
}

altimin's avatar
altimin committed
205 206 207 208 209 210 211 212 213 214 215
IN_PROC_BROWSER_TEST_F(HeadlessBrowserTest, UserDataDir) {
  // We do not want to bother with posting tasks to create a temp dir.
  // Just allow IO from main thread for now.
  base::ThreadRestrictions::SetIOAllowed(true);

  EXPECT_TRUE(embedded_test_server()->Start());

  base::ScopedTempDir user_data_dir;
  ASSERT_TRUE(user_data_dir.CreateUniqueTempDir());

  // Newly created temp directory should be empty.
216
  EXPECT_TRUE(base::IsDirectoryEmpty(user_data_dir.GetPath()));
altimin's avatar
altimin committed
217

218
  HeadlessBrowserContext* browser_context =
altimin's avatar
altimin committed
219 220
      browser()
          ->CreateBrowserContextBuilder()
221
          .SetUserDataDir(user_data_dir.GetPath())
altimin's avatar
altimin committed
222
          .SetIncognitoMode(false)
altimin's avatar
altimin committed
223 224 225 226 227 228 229 230 231 232 233 234
          .Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/hello.html"))
          .Build();

  EXPECT_TRUE(WaitForLoad(web_contents));

  // Something should be written to this directory.
  // If it is not the case, more complex page may be needed.
  // ServiceWorkers may be a good option.
235
  EXPECT_FALSE(base::IsDirectoryEmpty(user_data_dir.GetPath()));
altimin's avatar
altimin committed
236 237
}

altimin's avatar
altimin committed
238 239 240 241 242 243 244 245 246 247 248
IN_PROC_BROWSER_TEST_F(HeadlessBrowserTest, IncognitoMode) {
  // We do not want to bother with posting tasks to create a temp dir.
  // Just allow IO from main thread for now.
  base::ThreadRestrictions::SetIOAllowed(true);

  EXPECT_TRUE(embedded_test_server()->Start());

  base::ScopedTempDir user_data_dir;
  ASSERT_TRUE(user_data_dir.CreateUniqueTempDir());

  // Newly created temp directory should be empty.
249
  EXPECT_TRUE(base::IsDirectoryEmpty(user_data_dir.GetPath()));
altimin's avatar
altimin committed
250 251 252 253

  HeadlessBrowserContext* browser_context =
      browser()
          ->CreateBrowserContextBuilder()
254
          .SetUserDataDir(user_data_dir.GetPath())
altimin's avatar
altimin committed
255 256 257 258 259 260 261 262 263 264 265 266
          .SetIncognitoMode(true)
          .Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/hello.html"))
          .Build();

  EXPECT_TRUE(WaitForLoad(web_contents));

  // Similar to test above, but now we are in incognito mode,
  // so nothing should be written to this directory.
267
  EXPECT_TRUE(base::IsDirectoryEmpty(user_data_dir.GetPath()));
altimin's avatar
altimin committed
268 269
}

270
}  // namespace headless