summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/extensions/file_browser_resource_throttle_browsertest.cc
blob: bcd4488ad207cbe0a05fcd26c5bf978c5236ef04 (plain)
1
2
3
4
5
6
7
8
9
10
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
51
52
53
54
55
56
57
58
59
60
61
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright (c) 2012 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 "base/message_loop.h"
#include "chrome/browser/chromeos/extensions/file_browser_handler.h"
#include "chrome/browser/chromeos/extensions/file_browser_resource_throttle.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/google_apis/test_server/http_server.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.cc"
#include "chrome/common/pref_names.cc"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/download_test_observer.h"
#include "testing/gmock/include/gmock/gmock.h"

using content::BrowserContext;
using content::BrowserThread;
using content::DownloadItem;
using content::DownloadManager;
using content::DownloadUrlParameters;
using content::ResourceController;
using content::WebContents;
using extensions::Event;
using extensions::ExtensionSystem;
using google_apis::test_server::HttpRequest;
using google_apis::test_server::HttpResponse;
using google_apis::test_server::HttpServer;
using testing::_;

namespace {

// Used in FileBrowserResourceThrottleExtensionApiTest.Basic test to mock the
// resource controller bound to the test resource throttle.
class MockResourceController : public ResourceController {
 public:
  virtual ~MockResourceController() {}
  MOCK_METHOD0(Cancel, void());
  MOCK_METHOD0(CancelAndIgnore, void());
  MOCK_METHOD1(CancelWithError, void(int error_code));
  MOCK_METHOD0(Resume, void());
};

// Creates and triggers a test FileBrowserResourceThrottle for the listed
// request parameters (child and routing id from which the request came,
// request's MIME type and URL), with extension info map |info_map| and resource
// controller |controller|.
// The created resource throttle is started by calling |WillProcessResponse|.
// Used in FileBrowserResourceThrottleExtensionApiTest.Basic test.
//
// Must be called on the IO thread.
void CreateAndTriggerThrottle(int child_id,
                              int routing_id,
                              const std::string& mime_type,
                              const GURL& url,
                              bool is_incognito,
                              scoped_refptr<ExtensionInfoMap> info_map,
                              ResourceController* controller) {
  typedef FileBrowserResourceThrottle::FileBrowserHandlerEventRouter
          HandlerEventRouter;
  scoped_ptr<FileBrowserResourceThrottle> throttle(
      FileBrowserResourceThrottle::CreateForTest(child_id, routing_id,
          mime_type, url, is_incognito, info_map,
          scoped_ptr<HandlerEventRouter>()));

  throttle->set_controller_for_testing(controller);

  bool defer;
  throttle->WillProcessResponse(&defer);
  EXPECT_FALSE(defer);
}

// Test server's request handler.
// Returns response that should be sent by the test server.
scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
  scoped_ptr<HttpResponse> response(new HttpResponse());

  // For relative path "/doc_path.doc", return success response with MIME type
  // "application/msword".
  if (request.relative_url == "/doc_path.doc") {
    response->set_code(google_apis::test_server::SUCCESS);
    response->set_content_type("application/msword");
    return response.Pass();
  }

  // For relative path "/test_path_attch.txt", return success response with
  // MIME type "plain/text" and content "txt content". Also, set content
  // disposition to be attachment.
  if (request.relative_url == "/text_path_attch.txt") {
    response->set_code(google_apis::test_server::SUCCESS);
    response->set_content("txt content");
    response->set_content_type("plain/text");
    response->AddCustomHeader("Content-Disposition",
                              "attachment; filename=test_path.txt");
    return response.Pass();
  }
  // For relative path "/test_path_attch.txt", return success response with
  // MIME type "plain/text" and content "txt content".
  if (request.relative_url == "/text_path.txt") {
    response->set_code(google_apis::test_server::SUCCESS);
    response->set_content("txt content");
    response->set_content_type("plain/text");
    return response.Pass();
  }

  // No other requests should be handled in the tests.
  EXPECT_TRUE(false) << "NOTREACHED!";
  response->set_code(google_apis::test_server::NOT_FOUND);
  return response.Pass();
}

// Tests to verify that resources are correctly intercepted by
// FileBrowserResourceThrottle.
// The test extension expects the resources that should be handed to the
// extension to have MIME type 'application/msword' and the resources that
// should be downloaded by the browser to have MIME type 'plain/text'.
class FileBrowserResourceThrottleExtensionApiTest : public ExtensionApiTest {
 public:
  FileBrowserResourceThrottleExtensionApiTest() {}

  virtual ~FileBrowserResourceThrottleExtensionApiTest() {
    // Clear the test extension from the white-list.
    FileBrowserHandler::set_extension_whitelisted_for_test(NULL);
  }

  virtual void SetUpOnMainThread() {
    // Init test server.
    test_server_.reset(new HttpServer());
    test_server_->InitializeAndWaitUntilReady();
    test_server_->RegisterRequestHandler(base::Bind(&HandleRequest));

    ExtensionApiTest::SetUpOnMainThread();
  }

  virtual void CleanUpOnMainThread() {
    // Tear down the test server.
    test_server_->ShutdownAndWaitUntilComplete();
    test_server_.reset();
    ExtensionApiTest::CleanUpOnMainThread();
  }

  void InitializeDownloadSettings() {
    ASSERT_TRUE(browser());
    ASSERT_TRUE(downloads_dir_.CreateUniqueTempDir());

    // Setup default downloads directory to the scoped tmp directory created for
    // the test.
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, downloads_dir_.path());
    // Ensure there are no prompts for download during the test.
    browser()->profile()->GetPrefs()->SetBoolean(
        prefs::kPromptForDownload, false);

    DownloadManager* manager = GetDownloadManager();
    DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
    manager->RemoveAllDownloads();
  }

  // Sends onExecuteContentHandler event with the MIME type "test/done" to the
  // test extension.
  // The test extension calls 'chrome.test.notifySuccess' when it receives the
  // event with the "test/done" MIME type (unless the 'chrome.test.notifyFail'
  // has already been called).
  void SendDoneEvent() {
    scoped_ptr<ListValue> event_args(new ListValue());
    event_args->Append(new base::StringValue("test/done"));
    event_args->Append(new base::StringValue("http://foo"));

    scoped_ptr<Event> event(new Event(
        "fileBrowserHandler.onExecuteContentHandler", event_args.Pass()));

    ExtensionSystem::Get(browser()->profile())->event_router()->
        DispatchEventToExtension(test_extension_id_, event.Pass());
  }

  // Loads the test extension and set's up its file_browser_handler to handle
  // 'application/msword' and 'plain/text' MIME types.
  // The extension will notify success when it detects an event with the MIME
  // type 'application/msword' and notify fail when it detects an event with the
  // MIME type 'plain/text'.
  const extensions::Extension* LoadTestExtension() {
    const extensions::Extension* extension = LoadExtension(
        test_data_dir_.AppendASCII("file_browser/handle_mime_type"));
    if (!extension)
      return NULL;

    FileBrowserHandler::List* handlers =
        FileBrowserHandler::GetHandlers(extension);
    if (!handlers || handlers->size() == 0u) {
      message_ = "No file browser handlers defined.";
      return NULL;
    }

    test_extension_id_ = extension->id();

    FileBrowserHandler::set_extension_whitelisted_for_test(&test_extension_id_);

    // The MIME type filters cannot be defined directly in the extension's
    // manifest because the extension installation would fail for the extension
    // that is not white-listed to handle MIME types with its file browser
    // handlers.
    FileBrowserHandler* file_browser_handler = const_cast<FileBrowserHandler*>(
        handlers->at(0).get());
    file_browser_handler->AddMIMEType("application/msword");
    file_browser_handler->AddMIMEType("plain/text");

    return extension;
  }

  // Returns the download manager for the current browser.
  DownloadManager* GetDownloadManager() const {
    DownloadManager* download_manager =
        BrowserContext::GetDownloadManager(browser()->profile());
    EXPECT_TRUE(download_manager);
    return download_manager;
  }

  // Deletes the download and waits until it's flushed.
  // The |manager| should have |download| in its list of downloads.
  void DeleteDownloadAndWaitForFlush(DownloadItem* download,
                                     DownloadManager* manager) {
    scoped_refptr<content::DownloadTestFlushObserver> flush_observer(
        new content::DownloadTestFlushObserver(manager));
    download->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);
    flush_observer->WaitForFlush();
  }

 protected:
  std::string test_extension_id_;
  // The HTTP server used in the tests.
  scoped_ptr<HttpServer> test_server_;
  base::ScopedTempDir downloads_dir_;
};

// Tests that invoking FileBrowserResourceThrottle with handleable MIME type
// actually invokes the fileBrowserHandler.onExecuteContnentHandler event.
IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest, Basic) {
  ASSERT_TRUE(LoadTestExtension()) << message_;

  ResultCatcher catcher;

  MockResourceController mock_resource_controller;
  EXPECT_CALL(mock_resource_controller, Cancel()).Times(0);
  EXPECT_CALL(mock_resource_controller, CancelAndIgnore()).Times(1);
  EXPECT_CALL(mock_resource_controller, CancelWithError(_)).Times(0);
  EXPECT_CALL(mock_resource_controller, Resume()).Times(0);

  // Get child and routing id from the current web contents (the real values
  // should be used so the FileBrowserHandlerEventRouter can correctly extract
  // profile from them).
  WebContents* web_contents = chrome::GetActiveWebContents(browser());
  ASSERT_TRUE(web_contents);
  int child_id = web_contents->GetRenderProcessHost()->GetID();
  int routing_id = web_contents->GetRoutingID();

  scoped_refptr<ExtensionInfoMap> info_map =
      extensions::ExtensionSystem::Get(browser()->profile())->info_map();

  // The resource throttle must be created and invoked on IO thread.
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
      base::Bind(&CreateAndTriggerThrottle, child_id, routing_id,
          "application/msword", GURL("http://foo"), false, info_map,
           &mock_resource_controller));

  // Wait for the test extension to received the onExecuteContentHandler event.
  EXPECT_TRUE(catcher.GetNextResult());
}

// Tests that navigating to a resource with a MIME type handleable by an
// installed, white-listed extension invokes the extension's
// onExecuteContentHandler event (and does not start a download).
IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest, Navigate) {
  ASSERT_TRUE(LoadTestExtension()) << message_;

  ResultCatcher catcher;

  ui_test_utils::NavigateToURL(browser(),
                               test_server_->GetURL("/doc_path.doc"));

  // Wait for the response from the test server.
  MessageLoop::current()->RunUntilIdle();

  // There should be no downloads started by the navigation.
  DownloadManager* download_manager = GetDownloadManager();
  std::vector<DownloadItem*> downloads;
  download_manager->GetAllDownloads(&downloads);
  ASSERT_EQ(0u, downloads.size());

  // The test extension should receive onExecuteContentHandler event with MIME
  // type 'application/msword' (and call chrome.test.notifySuccess).
  EXPECT_TRUE(catcher.GetNextResult());
}

// Tests that navigation to an attachment starts a download, even if there is an
// extension with a file browser handler that can handle the attachment's MIME
// type.
IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest,
                       NavigateToAnAttachment) {
  InitializeDownloadSettings();

  ASSERT_TRUE(LoadTestExtension()) << message_;

  ResultCatcher catcher;

  // The test should start a downloadm.
  DownloadManager* download_manager = GetDownloadManager();
  scoped_ptr<content::DownloadTestObserver> download_observer(
      new content::DownloadTestObserverInProgress(download_manager, 1));

  ui_test_utils::NavigateToURL(browser(),
                               test_server_->GetURL("/text_path_attch.txt"));

  // Wait for the download to start.
  download_observer->WaitForFinished();

  // There should be one download started by the navigation.
  DownloadManager::DownloadVector downloads;
  download_manager->GetAllDownloads(&downloads);
  ASSERT_EQ(1u, downloads.size());

  // Cancel and delete the download started in the test.
  DeleteDownloadAndWaitForFlush(downloads[0], download_manager);

  // The test extension should not receive any events by now. Send it an event
  // with MIME type "test/done", so it stops waiting for the events. (If there
  // was an event with MIME type 'plain/text', |catcher.GetNextResult()| will
  // fail regardless of the sent event; chrome.test.notifySuccess will not be
  // called by the extension).
  SendDoneEvent();
  EXPECT_TRUE(catcher.GetNextResult());
}

// Tests that direct download requests don't get intercepted by
// FileBrowserResourceThrottle, even if there is an extension with a file
// browser handler that can handle the download's MIME type.
IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest,
                       DirectDownload) {
  InitializeDownloadSettings();

  ASSERT_TRUE(LoadTestExtension()) << message_;

  ResultCatcher catcher;

  DownloadManager* download_manager = GetDownloadManager();
  scoped_ptr<content::DownloadTestObserver> download_observer(
      new content::DownloadTestObserverInProgress(download_manager, 1));

  // The resource's URL on the test server.
  GURL url = test_server_->GetURL("/text_path.txt");

  // The download's target file path.
  FilePath target_path =
      downloads_dir_.path().Append(FILE_PATH_LITERAL("download_target.txt"));

  // Set the downloads parameters.
  content::WebContents* web_contents = chrome::GetActiveWebContents(browser());
  ASSERT_TRUE(web_contents);
  scoped_ptr<DownloadUrlParameters> params(
      DownloadUrlParameters::FromWebContents(web_contents, url));
  params->set_file_path(target_path);

  // Start download of the URL with a path "/text_path.txt" on the test server.
  download_manager->DownloadUrl(params.Pass());

  // Wait for the download to start.
  download_observer->WaitForFinished();

  // There should have been one download.
  std::vector<DownloadItem*> downloads;
  download_manager->GetAllDownloads(&downloads);
  ASSERT_EQ(1u, downloads.size());

  // Cancel and delete the download statred in the test.
  DeleteDownloadAndWaitForFlush(downloads[0], download_manager);

  // The test extension should not receive any events by now. Send it an event
  // with MIME type "test/done", so it stops waiting for the events. (If there
  // was an event with MIME type 'plain/text', |catcher.GetNextResult()| will
  // fail regardless of the sent event; chrome.test.notifySuccess will not be
  // called by the extension).
  SendDoneEvent();
  EXPECT_TRUE(catcher.GetNextResult());
}

}  // namespace