1 // Copyright (c) 2012 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 <algorithm> 6 #include <string> 7 #include <vector> 8 9 #include "base/bind.h" 10 #include "base/bind_helpers.h" 11 #include "base/callback.h" 12 #include "base/command_line.h" 13 #include "base/file_util.h" 14 #include "base/files/file_enumerator.h" 15 #include "base/files/file_path.h" 16 #include "base/files/scoped_temp_dir.h" 17 #include "base/memory/ref_counted.h" 18 #include "base/path_service.h" 19 #include "base/prefs/pref_service.h" 20 #include "base/run_loop.h" 21 #include "base/strings/string16.h" 22 #include "base/strings/string_util.h" 23 #include "base/strings/stringprintf.h" 24 #include "base/strings/utf_string_conversions.h" 25 #include "base/test/test_file_util.h" 26 #include "base/time/time.h" 27 #include "base/values.h" 28 #include "chrome/app/chrome_command_ids.h" 29 #include "chrome/browser/autocomplete/autocomplete_controller.h" 30 #include "chrome/browser/background/background_contents_service.h" 31 #include "chrome/browser/browser_process.h" 32 #include "chrome/browser/chrome_notification_types.h" 33 #include "chrome/browser/content_settings/tab_specific_content_settings.h" 34 #include "chrome/browser/devtools/devtools_window.h" 35 #include "chrome/browser/download/download_prefs.h" 36 #include "chrome/browser/extensions/crx_installer.h" 37 #include "chrome/browser/extensions/extension_host.h" 38 #include "chrome/browser/extensions/extension_service.h" 39 #include "chrome/browser/extensions/extension_system.h" 40 #include "chrome/browser/extensions/unpacked_installer.h" 41 #include "chrome/browser/extensions/updater/extension_updater.h" 42 #include "chrome/browser/infobars/infobar.h" 43 #include "chrome/browser/infobars/infobar_service.h" 44 #include "chrome/browser/media/media_capture_devices_dispatcher.h" 45 #include "chrome/browser/media/media_stream_devices_controller.h" 46 #include "chrome/browser/metrics/variations/variations_service.h" 47 #include "chrome/browser/net/url_request_mock_util.h" 48 #include "chrome/browser/plugins/plugin_prefs.h" 49 #include "chrome/browser/policy/browser_policy_connector.h" 50 #include "chrome/browser/policy/cloud/test_request_interceptor.h" 51 #include "chrome/browser/policy/profile_policy_connector.h" 52 #include "chrome/browser/policy/profile_policy_connector_factory.h" 53 #include "chrome/browser/prefs/session_startup_pref.h" 54 #include "chrome/browser/profiles/profile.h" 55 #include "chrome/browser/search/instant_service.h" 56 #include "chrome/browser/search/instant_service_factory.h" 57 #include "chrome/browser/search/search.h" 58 #include "chrome/browser/search_engines/template_url.h" 59 #include "chrome/browser/search_engines/template_url_service.h" 60 #include "chrome/browser/search_engines/template_url_service_factory.h" 61 #include "chrome/browser/translate/translate_infobar_delegate.h" 62 #include "chrome/browser/translate/translate_tab_helper.h" 63 #include "chrome/browser/ui/bookmarks/bookmark_bar.h" 64 #include "chrome/browser/ui/browser.h" 65 #include "chrome/browser/ui/browser_commands.h" 66 #include "chrome/browser/ui/browser_list.h" 67 #include "chrome/browser/ui/browser_tabstrip.h" 68 #include "chrome/browser/ui/browser_window.h" 69 #include "chrome/browser/ui/host_desktop.h" 70 #include "chrome/browser/ui/omnibox/location_bar.h" 71 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h" 72 #include "chrome/browser/ui/omnibox/omnibox_view.h" 73 #include "chrome/browser/ui/tabs/tab_strip_model.h" 74 #include "chrome/common/chrome_paths.h" 75 #include "chrome/common/chrome_switches.h" 76 #include "chrome/common/content_settings.h" 77 #include "chrome/common/content_settings_pattern.h" 78 #include "chrome/common/extensions/extension_constants.h" 79 #include "chrome/common/extensions/extension_set.h" 80 #include "chrome/common/pref_names.h" 81 #include "chrome/common/url_constants.h" 82 #include "chrome/test/base/in_process_browser_test.h" 83 #include "chrome/test/base/test_switches.h" 84 #include "chrome/test/base/ui_test_utils.h" 85 #include "components/policy/core/common/external_data_fetcher.h" 86 #include "components/policy/core/common/mock_configuration_policy_provider.h" 87 #include "components/policy/core/common/policy_map.h" 88 #include "components/policy/core/common/policy_service.h" 89 #include "components/policy/core/common/policy_service_impl.h" 90 #include "content/public/browser/browser_child_process_host_iterator.h" 91 #include "content/public/browser/browser_context.h" 92 #include "content/public/browser/browser_thread.h" 93 #include "content/public/browser/child_process_data.h" 94 #include "content/public/browser/download_item.h" 95 #include "content/public/browser/download_manager.h" 96 #include "content/public/browser/gpu_data_manager.h" 97 #include "content/public/browser/notification_details.h" 98 #include "content/public/browser/notification_observer.h" 99 #include "content/public/browser/notification_registrar.h" 100 #include "content/public/browser/notification_service.h" 101 #include "content/public/browser/notification_source.h" 102 #include "content/public/browser/notification_types.h" 103 #include "content/public/browser/plugin_service.h" 104 #include "content/public/browser/render_process_host.h" 105 #include "content/public/browser/render_view_host.h" 106 #include "content/public/browser/web_contents.h" 107 #include "content/public/common/content_constants.h" 108 #include "content/public/common/content_paths.h" 109 #include "content/public/common/page_transition_types.h" 110 #include "content/public/common/process_type.h" 111 #include "content/public/common/result_codes.h" 112 #include "content/public/common/url_constants.h" 113 #include "content/public/common/webplugininfo.h" 114 #include "content/public/test/browser_test_utils.h" 115 #include "content/public/test/download_test_observer.h" 116 #include "content/public/test/mock_notification_observer.h" 117 #include "content/public/test/test_navigation_observer.h" 118 #include "content/public/test/test_utils.h" 119 #include "content/test/net/url_request_failed_job.h" 120 #include "content/test/net/url_request_mock_http_job.h" 121 #include "extensions/browser/process_manager.h" 122 #include "extensions/common/constants.h" 123 #include "extensions/common/extension.h" 124 #include "grit/generated_resources.h" 125 #include "net/base/net_errors.h" 126 #include "net/base/net_util.h" 127 #include "net/base/url_util.h" 128 #include "net/http/http_stream_factory.h" 129 #include "net/url_request/url_request.h" 130 #include "net/url_request/url_request_filter.h" 131 #include "policy/policy_constants.h" 132 #include "testing/gmock/include/gmock/gmock.h" 133 #include "testing/gtest/include/gtest/gtest.h" 134 #include "third_party/WebKit/public/web/WebInputEvent.h" 135 #include "ui/base/l10n/l10n_util.h" 136 #include "ui/base/resource/resource_bundle.h" 137 #include "url/gurl.h" 138 139 #if defined(OS_CHROMEOS) 140 #include "ash/accelerators/accelerator_controller.h" 141 #include "ash/accelerators/accelerator_table.h" 142 #include "ash/magnifier/magnifier_constants.h" 143 #include "ash/shell.h" 144 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" 145 #include "chrome/browser/chromeos/accessibility/magnification_manager.h" 146 #include "chrome/browser/profiles/profile_manager.h" 147 #include "chromeos/audio/cras_audio_handler.h" 148 #endif 149 150 #if !defined(OS_MACOSX) 151 #include "apps/shell_window.h" 152 #include "apps/shell_window_registry.h" 153 #include "apps/ui/native_app_window.h" 154 #include "base/basictypes.h" 155 #include "base/compiler_specific.h" 156 #include "chrome/browser/ui/extensions/application_launch.h" 157 #include "ui/base/window_open_disposition.h" 158 #endif 159 160 using content::BrowserThread; 161 using content::URLRequestMockHTTPJob; 162 using testing::Mock; 163 using testing::Return; 164 using testing::_; 165 166 namespace policy { 167 168 namespace { 169 170 #if defined(OS_CHROMEOS) 171 const int kOneHourInMs = 60 * 60 * 1000; 172 const int kThreeHoursInMs = 180 * 60 * 1000; 173 #endif 174 175 const char kURL[] = "http://example.com"; 176 const char kCookieValue[] = "converted=true"; 177 // Assigned to Philip J. Fry to fix eventually. 178 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT"; 179 180 const base::FilePath::CharType kTestExtensionsDir[] = 181 FILE_PATH_LITERAL("extensions"); 182 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx"); 183 const base::FilePath::CharType kAdBlockCrxName[] = 184 FILE_PATH_LITERAL("adblock.crx"); 185 const base::FilePath::CharType kHostedAppCrxName[] = 186 FILE_PATH_LITERAL("hosted_app.crx"); 187 188 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; 189 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn"; 190 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi"; 191 192 const base::FilePath::CharType kGood2CrxManifestName[] = 193 FILE_PATH_LITERAL("good2_update_manifest.xml"); 194 const base::FilePath::CharType kGoodV1CrxManifestName[] = 195 FILE_PATH_LITERAL("good_v1_update_manifest.xml"); 196 const base::FilePath::CharType kGoodUnpackedExt[] = 197 FILE_PATH_LITERAL("good_unpacked"); 198 const base::FilePath::CharType kAppUnpackedExt[] = 199 FILE_PATH_LITERAL("app"); 200 201 #if !defined(OS_MACOSX) 202 const base::FilePath::CharType kUnpackedFullscreenAppName[] = 203 FILE_PATH_LITERAL("fullscreen_app"); 204 #endif // !defined(OS_MACOSX) 205 206 // Filters requests to the hosts in |urls| and redirects them to the test data 207 // dir through URLRequestMockHTTPJobs. 208 void RedirectHostsToTestData(const char* const urls[], size_t size) { 209 // Map the given hosts to the test data dir. 210 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 211 base::FilePath base_path; 212 PathService::Get(chrome::DIR_TEST_DATA, &base_path); 213 for (size_t i = 0; i < size; ++i) { 214 const GURL url(urls[i]); 215 EXPECT_TRUE(url.is_valid()); 216 filter->AddUrlProtocolHandler(url, 217 URLRequestMockHTTPJob::CreateProtocolHandler(base_path)); 218 } 219 } 220 221 // Remove filters for requests to the hosts in |urls|. 222 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) { 223 // Map the given hosts to the test data dir. 224 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 225 for (size_t i = 0; i < size; ++i) { 226 const GURL url(urls[i]); 227 EXPECT_TRUE(url.is_valid()); 228 filter->RemoveUrlHandler(url); 229 } 230 } 231 232 // Fails requests using ERR_CONNECTION_RESET. 233 net::URLRequestJob* FailedJobFactory( 234 net::URLRequest* request, 235 net::NetworkDelegate* network_delegate, 236 const std::string& scheme) { 237 return new content::URLRequestFailedJob( 238 request, network_delegate, net::ERR_CONNECTION_RESET); 239 } 240 241 // While |MakeRequestFail| is in scope URLRequests to |host| will fail. 242 class MakeRequestFail { 243 public: 244 // Sets up the filter on IO thread such that requests to |host| fail. 245 explicit MakeRequestFail(const std::string& host) : host_(host) { 246 BrowserThread::PostTaskAndReply( 247 BrowserThread::IO, FROM_HERE, 248 base::Bind(MakeRequestFailOnIO, host_), 249 base::MessageLoop::QuitClosure()); 250 content::RunMessageLoop(); 251 } 252 ~MakeRequestFail() { 253 BrowserThread::PostTaskAndReply( 254 BrowserThread::IO, FROM_HERE, 255 base::Bind(UndoMakeRequestFailOnIO, host_), 256 base::MessageLoop::QuitClosure()); 257 content::RunMessageLoop(); 258 } 259 260 private: 261 // Filters requests to the |host| such that they fail. Run on IO thread. 262 static void MakeRequestFailOnIO(const std::string& host) { 263 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 264 filter->AddHostnameHandler("http", host, &FailedJobFactory); 265 filter->AddHostnameHandler("https", host, &FailedJobFactory); 266 } 267 268 // Remove filters for requests to the |host|. Run on IO thread. 269 static void UndoMakeRequestFailOnIO(const std::string& host) { 270 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 271 filter->RemoveHostnameHandler("http", host); 272 filter->RemoveHostnameHandler("https", host); 273 } 274 275 const std::string host_; 276 }; 277 278 // Verifies that the given url |spec| can be opened. This assumes that |spec| 279 // points at empty.html in the test data dir. 280 void CheckCanOpenURL(Browser* browser, const char* spec) { 281 GURL url(spec); 282 ui_test_utils::NavigateToURL(browser, url); 283 content::WebContents* contents = 284 browser->tab_strip_model()->GetActiveWebContents(); 285 EXPECT_EQ(url, contents->GetURL()); 286 base::string16 title = UTF8ToUTF16(url.spec() + " was blocked"); 287 EXPECT_NE(title, contents->GetTitle()); 288 } 289 290 // Verifies that access to the given url |spec| is blocked. 291 void CheckURLIsBlocked(Browser* browser, const char* spec) { 292 GURL url(spec); 293 ui_test_utils::NavigateToURL(browser, url); 294 content::WebContents* contents = 295 browser->tab_strip_model()->GetActiveWebContents(); 296 EXPECT_EQ(url, contents->GetURL()); 297 base::string16 title = UTF8ToUTF16(url.spec() + " was blocked"); 298 EXPECT_EQ(title, contents->GetTitle()); 299 300 // Verify that the expected error page is being displayed. 301 bool result = false; 302 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 303 contents, 304 "var textContent = document.body.textContent;" 305 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;" 306 "domAutomationController.send(hasError);", 307 &result)); 308 EXPECT_TRUE(result); 309 } 310 311 #if !defined(OS_CHROMEOS) 312 // Downloads a file named |file| and expects it to be saved to |dir|, which 313 // must be empty. 314 void DownloadAndVerifyFile( 315 Browser* browser, const base::FilePath& dir, const base::FilePath& file) { 316 content::DownloadManager* download_manager = 317 content::BrowserContext::GetDownloadManager(browser->profile()); 318 content::DownloadTestObserverTerminal observer( 319 download_manager, 1, 320 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); 321 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 322 base::FilePath downloaded = dir.Append(file); 323 EXPECT_FALSE(base::PathExists(downloaded)); 324 ui_test_utils::NavigateToURLWithDisposition( 325 browser, url, CURRENT_TAB, 326 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 327 observer.WaitForFinished(); 328 EXPECT_EQ( 329 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE)); 330 EXPECT_TRUE(base::PathExists(downloaded)); 331 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES); 332 EXPECT_EQ(file, enumerator.Next().BaseName()); 333 EXPECT_EQ(base::FilePath(), enumerator.Next()); 334 } 335 336 #else 337 338 int CountScreenshots() { 339 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext( 340 ProfileManager::GetActiveUserProfileOrOffTheRecord()); 341 base::FileEnumerator enumerator(download_prefs->DownloadPath(), 342 false, base::FileEnumerator::FILES, 343 "Screenshot*"); 344 int count = 0; 345 while (!enumerator.Next().empty()) 346 count++; 347 return count; 348 } 349 #endif 350 351 // Checks if WebGL is enabled in the given WebContents. 352 bool IsWebGLEnabled(content::WebContents* contents) { 353 bool result = false; 354 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 355 contents, 356 "var canvas = document.createElement('canvas');" 357 "var context = canvas.getContext('webgl');" 358 "domAutomationController.send(context != null);", 359 &result)); 360 return result; 361 } 362 363 bool IsJavascriptEnabled(content::WebContents* contents) { 364 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue( 365 contents->GetRenderViewHost(), "123"); 366 int result = 0; 367 if (!value->GetAsInteger(&result)) 368 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType()); 369 return result == 123; 370 } 371 372 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out, 373 const std::vector<content::WebPluginInfo>& in) { 374 *out = in; 375 base::MessageLoop::current()->QuitWhenIdle(); 376 } 377 378 template<typename T> 379 void CopyValueAndQuit(T* out, T in) { 380 *out = in; 381 base::MessageLoop::current()->QuitWhenIdle(); 382 } 383 384 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) { 385 content::PluginService* service = content::PluginService::GetInstance(); 386 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins)); 387 content::RunMessageLoop(); 388 } 389 390 const content::WebPluginInfo* GetFlashPlugin( 391 const std::vector<content::WebPluginInfo>& plugins) { 392 const content::WebPluginInfo* flash = NULL; 393 for (size_t i = 0; i < plugins.size(); ++i) { 394 if (plugins[i].name == ASCIIToUTF16(content::kFlashPluginName)) { 395 flash = &plugins[i]; 396 break; 397 } 398 } 399 #if defined(OFFICIAL_BUILD) 400 // Official builds bundle Flash. 401 EXPECT_TRUE(flash); 402 #else 403 if (!flash) 404 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found."; 405 #endif 406 return flash; 407 } 408 409 bool SetPluginEnabled(PluginPrefs* plugin_prefs, 410 const content::WebPluginInfo* plugin, 411 bool enabled) { 412 bool ok = false; 413 plugin_prefs->EnablePlugin(enabled, plugin->path, 414 base::Bind(CopyValueAndQuit<bool>, &ok)); 415 content::RunMessageLoop(); 416 return ok; 417 } 418 419 int CountPluginsOnIOThread() { 420 int count = 0; 421 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) { 422 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN || 423 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) { 424 count++; 425 } 426 } 427 return count; 428 } 429 430 int CountPlugins() { 431 int count = -1; 432 BrowserThread::PostTaskAndReplyWithResult( 433 BrowserThread::IO, FROM_HERE, 434 base::Bind(CountPluginsOnIOThread), 435 base::Bind(CopyValueAndQuit<int>, &count)); 436 content::RunMessageLoop(); 437 EXPECT_GE(count, 0); 438 return count; 439 } 440 441 void FlushBlacklistPolicy() { 442 // Updates of the URLBlacklist are done on IO, after building the blacklist 443 // on FILE, which is initiated from IO. 444 content::RunAllPendingInMessageLoop(BrowserThread::IO); 445 content::RunAllPendingInMessageLoop(BrowserThread::FILE); 446 content::RunAllPendingInMessageLoop(BrowserThread::IO); 447 } 448 449 bool ContainsVisibleElement(content::WebContents* contents, 450 const std::string& id) { 451 bool result; 452 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 453 contents, 454 "var elem = document.getElementById('" + id + "');" 455 "domAutomationController.send(!!elem && !elem.hidden);", 456 &result)); 457 return result; 458 } 459 460 #if defined(OS_CHROMEOS) 461 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver { 462 public: 463 TestAudioObserver() : output_mute_changed_count_(0) { 464 } 465 466 int output_mute_changed_count() const { 467 return output_mute_changed_count_; 468 } 469 470 virtual ~TestAudioObserver() {} 471 472 protected: 473 // chromeos::CrasAudioHandler::AudioObserver overrides. 474 virtual void OnOutputMuteChanged() OVERRIDE { 475 ++output_mute_changed_count_; 476 } 477 478 private: 479 int output_mute_changed_count_; 480 481 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver); 482 }; 483 #endif 484 485 // This class waits until either a load stops or the WebContents is destroyed. 486 class WebContentsLoadedOrDestroyedWatcher 487 : public content::WebContentsObserver { 488 public: 489 explicit WebContentsLoadedOrDestroyedWatcher( 490 content::WebContents* web_contents); 491 virtual ~WebContentsLoadedOrDestroyedWatcher(); 492 493 // Waits until the WebContents's load is done or until it is destroyed. 494 void Wait(); 495 496 // Overridden WebContentsObserver methods. 497 virtual void WebContentsDestroyed( 498 content::WebContents* web_contents) OVERRIDE; 499 virtual void DidStopLoading( 500 content::RenderViewHost* render_view_host) OVERRIDE; 501 502 private: 503 scoped_refptr<content::MessageLoopRunner> message_loop_runner_; 504 505 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher); 506 }; 507 508 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher( 509 content::WebContents* web_contents) 510 : content::WebContentsObserver(web_contents), 511 message_loop_runner_(new content::MessageLoopRunner) { 512 } 513 514 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {} 515 516 void WebContentsLoadedOrDestroyedWatcher::Wait() { 517 message_loop_runner_->Run(); 518 } 519 520 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed( 521 content::WebContents* web_contents) { 522 message_loop_runner_->Quit(); 523 } 524 525 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading( 526 content::RenderViewHost* render_view_host) { 527 message_loop_runner_->Quit(); 528 } 529 530 #if !defined(OS_MACOSX) 531 532 // Observer used to wait for the creation of a new shell window. 533 class TestAddShellWindowObserver : public apps::ShellWindowRegistry::Observer { 534 public: 535 explicit TestAddShellWindowObserver(apps::ShellWindowRegistry* registry); 536 virtual ~TestAddShellWindowObserver(); 537 538 // apps::ShellWindowRegistry::Observer: 539 virtual void OnShellWindowAdded(apps::ShellWindow* shell_window) OVERRIDE; 540 virtual void OnShellWindowIconChanged( 541 apps::ShellWindow* shell_window) OVERRIDE; 542 virtual void OnShellWindowRemoved(apps::ShellWindow* shell_window) OVERRIDE; 543 544 apps::ShellWindow* WaitForShellWindow(); 545 546 private: 547 apps::ShellWindowRegistry* registry_; // Not owned. 548 apps::ShellWindow* window_; // Not owned. 549 base::RunLoop run_loop_; 550 551 DISALLOW_COPY_AND_ASSIGN(TestAddShellWindowObserver); 552 }; 553 554 TestAddShellWindowObserver::TestAddShellWindowObserver( 555 apps::ShellWindowRegistry* registry) 556 : registry_(registry), 557 window_(NULL) { 558 registry_->AddObserver(this); 559 } 560 561 TestAddShellWindowObserver::~TestAddShellWindowObserver() { 562 registry_->RemoveObserver(this); 563 } 564 565 void TestAddShellWindowObserver::OnShellWindowAdded( 566 apps::ShellWindow* shell_window) { 567 window_ = shell_window; 568 run_loop_.Quit(); 569 } 570 571 void TestAddShellWindowObserver::OnShellWindowIconChanged( 572 apps::ShellWindow* shell_window) { 573 } 574 575 void TestAddShellWindowObserver::OnShellWindowRemoved( 576 apps::ShellWindow* shell_window) { 577 } 578 579 apps::ShellWindow* TestAddShellWindowObserver::WaitForShellWindow() { 580 run_loop_.Run(); 581 return window_; 582 } 583 584 #endif 585 586 } // namespace 587 588 class PolicyTest : public InProcessBrowserTest { 589 protected: 590 PolicyTest() {} 591 virtual ~PolicyTest() {} 592 593 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 594 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs"); 595 EXPECT_CALL(provider_, IsInitializationComplete(_)) 596 .WillRepeatedly(Return(true)); 597 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); 598 } 599 600 virtual void SetUpOnMainThread() OVERRIDE { 601 BrowserThread::PostTask( 602 BrowserThread::IO, FROM_HERE, 603 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true)); 604 } 605 606 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA 607 // instead of chrome::DIR_TEST_DATA. 608 void ServeContentTestData() { 609 base::FilePath root_http; 610 PathService::Get(content::DIR_TEST_DATA, &root_http); 611 BrowserThread::PostTaskAndReply( 612 BrowserThread::IO, FROM_HERE, 613 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http), 614 base::MessageLoop::current()->QuitWhenIdleClosure()); 615 content::RunMessageLoop(); 616 } 617 618 void SetScreenshotPolicy(bool enabled) { 619 PolicyMap policies; 620 policies.Set(key::kDisableScreenshots, 621 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 622 base::Value::CreateBooleanValue(!enabled), NULL); 623 UpdateProviderPolicy(policies); 624 } 625 626 #if defined(OS_CHROMEOS) 627 void TestScreenshotFile(bool enabled) { 628 SetScreenshotPolicy(enabled); 629 ash::Shell::GetInstance()->accelerator_controller()->PerformAction( 630 ash::TAKE_SCREENSHOT, ui::Accelerator()); 631 632 // TAKE_SCREENSHOT handler posts write file task on success, wait for it. 633 BrowserThread::PostTaskAndReply( 634 BrowserThread::IO, 635 FROM_HERE, 636 base::Bind(base::DoNothing), 637 base::MessageLoop::QuitClosure()); 638 content::RunMessageLoop(); 639 } 640 #endif 641 642 ExtensionService* extension_service() { 643 extensions::ExtensionSystem* system = 644 extensions::ExtensionSystem::Get(browser()->profile()); 645 return system->extension_service(); 646 } 647 648 const extensions::Extension* InstallExtension( 649 const base::FilePath::StringType& name) { 650 base::FilePath extension_path(ui_test_utils::GetTestFilePath( 651 base::FilePath(kTestExtensionsDir), base::FilePath(name))); 652 scoped_refptr<extensions::CrxInstaller> installer = 653 extensions::CrxInstaller::CreateSilent(extension_service()); 654 installer->set_allow_silent_install(true); 655 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE); 656 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE); 657 658 content::WindowedNotificationObserver observer( 659 chrome::NOTIFICATION_CRX_INSTALLER_DONE, 660 content::NotificationService::AllSources()); 661 installer->InstallCrx(extension_path); 662 observer.Wait(); 663 content::Details<const extensions::Extension> details = observer.details(); 664 return details.ptr(); 665 } 666 667 const extensions::Extension* LoadUnpackedExtension( 668 const base::FilePath::StringType& name, bool expect_success) { 669 base::FilePath extension_path(ui_test_utils::GetTestFilePath( 670 base::FilePath(kTestExtensionsDir), base::FilePath(name))); 671 scoped_refptr<extensions::UnpackedInstaller> installer = 672 extensions::UnpackedInstaller::Create(extension_service()); 673 content::WindowedNotificationObserver observer( 674 expect_success ? chrome::NOTIFICATION_EXTENSION_LOADED 675 : chrome::NOTIFICATION_EXTENSION_LOAD_ERROR, 676 content::NotificationService::AllSources()); 677 installer->Load(extension_path); 678 observer.Wait(); 679 680 const ExtensionSet* extensions = extension_service()->extensions(); 681 for (ExtensionSet::const_iterator it = extensions->begin(); 682 it != extensions->end(); ++it) { 683 if ((*it)->path() == extension_path) 684 return it->get(); 685 } 686 return NULL; 687 } 688 689 void UninstallExtension(const std::string& id, bool expect_success) { 690 content::WindowedNotificationObserver observer( 691 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED 692 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED, 693 content::NotificationService::AllSources()); 694 extension_service()->UninstallExtension(id, false, NULL); 695 observer.Wait(); 696 } 697 698 void UpdateProviderPolicy(const PolicyMap& policy) { 699 provider_.UpdateChromePolicy(policy); 700 DCHECK(base::MessageLoop::current()); 701 base::RunLoop loop; 702 loop.RunUntilIdle(); 703 } 704 705 // Sends a mouse click at the given coordinates to the current renderer. 706 void PerformClick(int x, int y) { 707 content::WebContents* contents = 708 browser()->tab_strip_model()->GetActiveWebContents(); 709 blink::WebMouseEvent click_event; 710 click_event.type = blink::WebInputEvent::MouseDown; 711 click_event.button = blink::WebMouseEvent::ButtonLeft; 712 click_event.clickCount = 1; 713 click_event.x = x; 714 click_event.y = y; 715 contents->GetRenderViewHost()->ForwardMouseEvent(click_event); 716 click_event.type = blink::WebInputEvent::MouseUp; 717 contents->GetRenderViewHost()->ForwardMouseEvent(click_event); 718 } 719 720 MockConfigurationPolicyProvider provider_; 721 }; 722 723 #if defined(OS_WIN) 724 // This policy only exists on Windows. 725 726 // Sets the locale policy before the browser is started. 727 class LocalePolicyTest : public PolicyTest { 728 public: 729 LocalePolicyTest() {} 730 virtual ~LocalePolicyTest() {} 731 732 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 733 PolicyTest::SetUpInProcessBrowserTestFixture(); 734 PolicyMap policies; 735 policies.Set( 736 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 737 base::Value::CreateStringValue("fr"), NULL); 738 provider_.UpdateChromePolicy(policies); 739 // The "en-US" ResourceBundle is always loaded before this step for tests, 740 // but in this test we want the browser to load the bundle as it 741 // normally would. 742 ResourceBundle::CleanupSharedInstance(); 743 } 744 }; 745 746 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) { 747 // Verifies that the default locale can be overridden with policy. 748 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); 749 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 750 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); 751 base::string16 title; 752 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title)); 753 EXPECT_EQ(french_title, title); 754 755 // Make sure this is really French and differs from the English title. 756 std::string loaded = 757 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US"); 758 EXPECT_EQ("en-US", loaded); 759 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); 760 EXPECT_NE(french_title, english_title); 761 } 762 #endif 763 764 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) { 765 #if defined(OS_WIN) && defined(USE_ASH) 766 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 767 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 768 return; 769 #endif 770 771 // Verifies that the bookmarks bar can be forced to always or never show up. 772 773 // Test starts in about:blank. 774 PrefService* prefs = browser()->profile()->GetPrefs(); 775 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 776 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 777 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state()); 778 779 PolicyMap policies; 780 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, 781 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 782 UpdateProviderPolicy(policies); 783 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 784 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 785 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state()); 786 787 // The NTP has special handling of the bookmark bar. 788 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 789 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state()); 790 791 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, 792 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 793 UpdateProviderPolicy(policies); 794 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 795 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 796 // The bookmark bar is hidden in the NTP when disabled by policy. 797 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state()); 798 799 policies.Clear(); 800 UpdateProviderPolicy(policies); 801 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 802 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 803 // The bookmark bar is shown detached in the NTP, when disabled by prefs only. 804 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state()); 805 } 806 807 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) { 808 // Verifies that cookies are deleted on shutdown. This test is split in 3 809 // parts because it spans 2 browser restarts. 810 811 Profile* profile = browser()->profile(); 812 GURL url(kURL); 813 // No cookies at startup. 814 EXPECT_TRUE(content::GetCookies(profile, url).empty()); 815 // Set a cookie now. 816 std::string value = std::string(kCookieValue) + std::string(kCookieOptions); 817 EXPECT_TRUE(content::SetCookie(profile, url, value)); 818 // Verify it was set. 819 EXPECT_EQ(kCookieValue, GetCookies(profile, url)); 820 } 821 822 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) { 823 // Verify that the cookie persists across restarts. 824 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL))); 825 // Now set the policy and the cookie should be gone after another restart. 826 PolicyMap policies; 827 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY, 828 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4), NULL); 829 UpdateProviderPolicy(policies); 830 } 831 832 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) { 833 // Verify that the cookie is gone. 834 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty()); 835 } 836 837 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) { 838 MakeRequestFail make_request_fail("search.example"); 839 840 // Verifies that a default search is made using the provider configured via 841 // policy. Also checks that default search can be completely disabled. 842 const base::string16 kKeyword(ASCIIToUTF16("testsearch")); 843 const std::string kSearchURL("http://search.example/search?q={searchTerms}"); 844 const std::string kAlternateURL0( 845 "http://search.example/search#q={searchTerms}"); 846 const std::string kAlternateURL1("http://search.example/#q={searchTerms}"); 847 const std::string kSearchTermsReplacementKey("zekey"); 848 const std::string kImageURL("http://test.com/searchbyimage/upload"); 849 const std::string kImageURLPostParams( 850 "image_content=content,image_url=http://test.com/test.png"); 851 const std::string kNewTabURL("http://search.example/newtab"); 852 853 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 854 browser()->profile()); 855 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 856 TemplateURL* default_search = service->GetDefaultSearchProvider(); 857 ASSERT_TRUE(default_search); 858 EXPECT_NE(kKeyword, default_search->keyword()); 859 EXPECT_NE(kSearchURL, default_search->url()); 860 EXPECT_FALSE( 861 default_search->alternate_urls().size() == 2 && 862 default_search->alternate_urls()[0] == kAlternateURL0 && 863 default_search->alternate_urls()[1] == kAlternateURL1 && 864 default_search->search_terms_replacement_key() == 865 kSearchTermsReplacementKey && 866 default_search->image_url() == kImageURL && 867 default_search->image_url_post_params() == kImageURLPostParams && 868 default_search->new_tab_url() == kNewTabURL); 869 870 // Override the default search provider using policies. 871 PolicyMap policies; 872 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 873 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 874 policies.Set(key::kDefaultSearchProviderKeyword, 875 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 876 base::Value::CreateStringValue(kKeyword), NULL); 877 policies.Set(key::kDefaultSearchProviderSearchURL, 878 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 879 base::Value::CreateStringValue(kSearchURL), NULL); 880 base::ListValue* alternate_urls = new base::ListValue(); 881 alternate_urls->AppendString(kAlternateURL0); 882 alternate_urls->AppendString(kAlternateURL1); 883 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY, 884 POLICY_SCOPE_USER, alternate_urls, NULL); 885 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey, 886 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 887 base::Value::CreateStringValue(kSearchTermsReplacementKey), 888 NULL); 889 policies.Set(key::kDefaultSearchProviderImageURL, 890 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 891 base::Value::CreateStringValue(kImageURL), 892 NULL); 893 policies.Set(key::kDefaultSearchProviderImageURLPostParams, 894 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 895 base::Value::CreateStringValue(kImageURLPostParams), 896 NULL); 897 policies.Set(key::kDefaultSearchProviderNewTabURL, 898 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 899 base::Value::CreateStringValue(kNewTabURL), 900 NULL); 901 UpdateProviderPolicy(policies); 902 default_search = service->GetDefaultSearchProvider(); 903 ASSERT_TRUE(default_search); 904 EXPECT_EQ(kKeyword, default_search->keyword()); 905 EXPECT_EQ(kSearchURL, default_search->url()); 906 EXPECT_EQ(2U, default_search->alternate_urls().size()); 907 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]); 908 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]); 909 EXPECT_EQ(kSearchTermsReplacementKey, 910 default_search->search_terms_replacement_key()); 911 EXPECT_EQ(kImageURL, default_search->image_url()); 912 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params()); 913 EXPECT_EQ(kNewTabURL, default_search->new_tab_url()); 914 915 // Verify that searching from the omnibox uses kSearchURL. 916 chrome::FocusLocationBar(browser()); 917 LocationBar* location_bar = browser()->window()->GetLocationBar(); 918 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for"); 919 OmniboxEditModel* model = location_bar->GetOmniboxView()->model(); 920 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid()); 921 content::WebContents* web_contents = 922 browser()->tab_strip_model()->GetActiveWebContents(); 923 GURL expected("http://search.example/search?q=stuff+to+search+for"); 924 EXPECT_EQ(expected, web_contents->GetURL()); 925 926 // Verify that searching from the omnibox can be disabled. 927 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL)); 928 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 929 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 930 EXPECT_TRUE(service->GetDefaultSearchProvider()); 931 UpdateProviderPolicy(policies); 932 EXPECT_FALSE(service->GetDefaultSearchProvider()); 933 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work"); 934 // This means that submitting won't trigger any action. 935 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid()); 936 EXPECT_EQ(GURL(content::kAboutBlankURL), web_contents->GetURL()); 937 } 938 939 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) { 940 // Add an individual proxy policy value. 941 PolicyMap policies; 942 policies.Set(key::kProxyServerMode, 943 POLICY_LEVEL_MANDATORY, 944 POLICY_SCOPE_USER, 945 base::Value::CreateIntegerValue(3), 946 NULL); 947 UpdateProviderPolicy(policies); 948 949 // It should be removed and replaced with a dictionary. 950 PolicyMap expected; 951 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue); 952 expected_value->SetInteger(key::kProxyServerMode, 3); 953 expected.Set(key::kProxySettings, 954 POLICY_LEVEL_MANDATORY, 955 POLICY_SCOPE_USER, 956 expected_value.release(), 957 NULL); 958 959 // Check both the browser and the profile. 960 const PolicyMap& actual_from_browser = 961 g_browser_process->browser_policy_connector() 962 ->GetPolicyService() 963 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); 964 EXPECT_TRUE(expected.Equals(actual_from_browser)); 965 const PolicyMap& actual_from_profile = 966 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile()) 967 ->policy_service() 968 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); 969 EXPECT_TRUE(expected.Equals(actual_from_profile)); 970 } 971 972 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) { 973 // Makes the requests fail since all we want to check is that the redirection 974 // is done properly. 975 MakeRequestFail make_request_fail("google.com"); 976 977 // Verifies that requests to Google Search engine with the SafeSearch 978 // enabled set the safe=active&ssui=on parameters at the end of the query. 979 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 980 browser()->profile()); 981 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 982 983 // First check that nothing happens. 984 content::TestNavigationObserver no_safesearch_observer( 985 browser()->tab_strip_model()->GetActiveWebContents()); 986 chrome::FocusLocationBar(browser()); 987 LocationBar* location_bar = browser()->window()->GetLocationBar(); 988 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/"); 989 OmniboxEditModel* model = location_bar->GetOmniboxView()->model(); 990 no_safesearch_observer.Wait(); 991 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid()); 992 content::WebContents* web_contents = 993 browser()->tab_strip_model()->GetActiveWebContents(); 994 GURL expected_without("http://google.com/"); 995 EXPECT_EQ(expected_without, web_contents->GetURL()); 996 997 PrefService* prefs = browser()->profile()->GetPrefs(); 998 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch)); 999 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch)); 1000 1001 // Override the default SafeSearch setting using policies. 1002 PolicyMap policies; 1003 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY, 1004 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1005 UpdateProviderPolicy(policies); 1006 1007 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch)); 1008 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch)); 1009 1010 content::TestNavigationObserver safesearch_observer( 1011 browser()->tab_strip_model()->GetActiveWebContents()); 1012 1013 // Verify that searching from google.com works. 1014 chrome::FocusLocationBar(browser()); 1015 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/"); 1016 safesearch_observer.Wait(); 1017 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid()); 1018 web_contents = browser()->tab_strip_model()->GetActiveWebContents(); 1019 std::string expected_url("http://google.com/?"); 1020 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" + 1021 chrome::kSafeSearchSsuiParameter; 1022 GURL expected_with_parameters(expected_url); 1023 EXPECT_EQ(expected_with_parameters, web_contents->GetURL()); 1024 } 1025 1026 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) { 1027 MakeRequestFail make_request_fail("search.example"); 1028 1029 chrome::EnableQueryExtractionForTesting(); 1030 1031 // Verifies that a default search is made using the provider configured via 1032 // policy. Also checks that default search can be completely disabled. 1033 const base::string16 kKeyword(ASCIIToUTF16("testsearch")); 1034 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}"); 1035 const std::string kInstantURL("http://does/not/exist"); 1036 const std::string kAlternateURL0( 1037 "https://www.google.com/search#q={searchTerms}"); 1038 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}"); 1039 const std::string kSearchTermsReplacementKey( 1040 "{google:instantExtendedEnabledKey}"); 1041 1042 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 1043 browser()->profile()); 1044 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 1045 TemplateURL* default_search = service->GetDefaultSearchProvider(); 1046 ASSERT_TRUE(default_search); 1047 EXPECT_NE(kKeyword, default_search->keyword()); 1048 EXPECT_NE(kSearchURL, default_search->url()); 1049 EXPECT_NE(kInstantURL, default_search->instant_url()); 1050 EXPECT_FALSE( 1051 default_search->alternate_urls().size() == 2 && 1052 default_search->alternate_urls()[0] == kAlternateURL0 && 1053 default_search->alternate_urls()[1] == kAlternateURL1); 1054 1055 // Override the default search provider using policies. 1056 PolicyMap policies; 1057 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 1058 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1059 policies.Set(key::kDefaultSearchProviderKeyword, 1060 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1061 base::Value::CreateStringValue(kKeyword), NULL); 1062 policies.Set(key::kDefaultSearchProviderSearchURL, 1063 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1064 base::Value::CreateStringValue(kSearchURL), NULL); 1065 policies.Set(key::kDefaultSearchProviderInstantURL, 1066 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1067 base::Value::CreateStringValue(kInstantURL), NULL); 1068 base::ListValue* alternate_urls = new base::ListValue(); 1069 alternate_urls->AppendString(kAlternateURL0); 1070 alternate_urls->AppendString(kAlternateURL1); 1071 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY, 1072 POLICY_SCOPE_USER, alternate_urls, NULL); 1073 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey, 1074 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1075 base::Value::CreateStringValue(kSearchTermsReplacementKey), 1076 NULL); 1077 UpdateProviderPolicy(policies); 1078 default_search = service->GetDefaultSearchProvider(); 1079 ASSERT_TRUE(default_search); 1080 EXPECT_EQ(kKeyword, default_search->keyword()); 1081 EXPECT_EQ(kSearchURL, default_search->url()); 1082 EXPECT_EQ(kInstantURL, default_search->instant_url()); 1083 EXPECT_EQ(2U, default_search->alternate_urls().size()); 1084 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]); 1085 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]); 1086 1087 // Query terms replacement requires that the renderer process be a recognized 1088 // Instant renderer. Fake it. 1089 InstantService* instant_service = 1090 InstantServiceFactory::GetForProfile(browser()->profile()); 1091 instant_service->AddInstantProcess(browser()->tab_strip_model()-> 1092 GetActiveWebContents()->GetRenderProcessHost()->GetID()); 1093 1094 // Verify that searching from the omnibox does search term replacement with 1095 // first URL pattern. 1096 chrome::FocusLocationBar(browser()); 1097 LocationBar* location_bar = browser()->window()->GetLocationBar(); 1098 OmniboxView* omnibox_view = location_bar->GetOmniboxView(); 1099 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 1100 "https://www.google.com/?espv=1#q=foobar"); 1101 EXPECT_TRUE( 1102 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false)); 1103 EXPECT_EQ(ASCIIToUTF16("foobar"), omnibox_view->GetText()); 1104 1105 // Verify that not using espv=1 does not do search term replacement. 1106 chrome::FocusLocationBar(browser()); 1107 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 1108 "https://www.google.com/?q=foobar"); 1109 EXPECT_FALSE( 1110 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false)); 1111 EXPECT_EQ(ASCIIToUTF16("https://www.google.com/?q=foobar"), 1112 omnibox_view->GetText()); 1113 1114 // Verify that searching from the omnibox does search term replacement with 1115 // second URL pattern. 1116 chrome::FocusLocationBar(browser()); 1117 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 1118 "https://www.google.com/search?espv=1#q=banana"); 1119 EXPECT_TRUE( 1120 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false)); 1121 EXPECT_EQ(ASCIIToUTF16("banana"), omnibox_view->GetText()); 1122 1123 // Verify that searching from the omnibox does search term replacement with 1124 // standard search URL pattern. 1125 chrome::FocusLocationBar(browser()); 1126 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 1127 "https://www.google.com/search?q=tractor+parts&espv=1"); 1128 EXPECT_TRUE( 1129 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false)); 1130 EXPECT_EQ(ASCIIToUTF16("tractor parts"), omnibox_view->GetText()); 1131 1132 // Verify that searching from the omnibox prioritizes hash over query. 1133 chrome::FocusLocationBar(browser()); 1134 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 1135 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar"); 1136 EXPECT_TRUE( 1137 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false)); 1138 EXPECT_EQ(ASCIIToUTF16("foobar"), omnibox_view->GetText()); 1139 } 1140 1141 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) { 1142 // This test assumes Gpu access. 1143 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL)) 1144 return; 1145 1146 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL)); 1147 // WebGL is enabled by default. 1148 content::WebContents* contents = 1149 browser()->tab_strip_model()->GetActiveWebContents(); 1150 EXPECT_TRUE(IsWebGLEnabled(contents)); 1151 // Disable with a policy. 1152 PolicyMap policies; 1153 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, 1154 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1155 UpdateProviderPolicy(policies); 1156 // Crash and reload the tab to get a new renderer. 1157 content::CrashTab(contents); 1158 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD)); 1159 EXPECT_FALSE(IsWebGLEnabled(contents)); 1160 // Enable with a policy. 1161 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, 1162 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1163 UpdateProviderPolicy(policies); 1164 content::CrashTab(contents); 1165 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD)); 1166 EXPECT_TRUE(IsWebGLEnabled(contents)); 1167 } 1168 1169 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) { 1170 // Verifies that SPDY can be disable by policy. 1171 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled()); 1172 PolicyMap policies; 1173 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY, 1174 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1175 UpdateProviderPolicy(policies); 1176 content::RunAllPendingInMessageLoop(); 1177 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled()); 1178 // Verify that it can be force-enabled too. 1179 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true); 1180 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY, 1181 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1182 UpdateProviderPolicy(policies); 1183 content::RunAllPendingInMessageLoop(); 1184 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled()); 1185 } 1186 1187 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) { 1188 // Verifies that plugins can be forced to be disabled by policy. 1189 1190 // Verify that the Flash plugin exists and that it can be enabled and disabled 1191 // by the user. 1192 std::vector<content::WebPluginInfo> plugins; 1193 GetPluginList(&plugins); 1194 const content::WebPluginInfo* flash = GetFlashPlugin(plugins); 1195 if (!flash) 1196 return; 1197 PluginPrefs* plugin_prefs = 1198 PluginPrefs::GetForProfile(browser()->profile()).get(); 1199 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1200 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 1201 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1202 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true)); 1203 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1204 1205 // Now disable it with a policy. 1206 base::ListValue disabled_plugins; 1207 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*")); 1208 PolicyMap policies; 1209 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 1210 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL); 1211 UpdateProviderPolicy(policies); 1212 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1213 // The user shouldn't be able to enable it. 1214 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true)); 1215 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1216 } 1217 1218 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) { 1219 // Verifies that plugins with an exception in the blacklist can be enabled. 1220 1221 // Verify that the Flash plugin exists and that it can be enabled and disabled 1222 // by the user. 1223 std::vector<content::WebPluginInfo> plugins; 1224 GetPluginList(&plugins); 1225 const content::WebPluginInfo* flash = GetFlashPlugin(plugins); 1226 if (!flash) 1227 return; 1228 PluginPrefs* plugin_prefs = 1229 PluginPrefs::GetForProfile(browser()->profile()).get(); 1230 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1231 1232 // Disable all plugins. 1233 base::ListValue disabled_plugins; 1234 disabled_plugins.Append(base::Value::CreateStringValue("*")); 1235 PolicyMap policies; 1236 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 1237 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL); 1238 UpdateProviderPolicy(policies); 1239 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1240 // The user shouldn't be able to enable it. 1241 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true)); 1242 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1243 1244 // Now open an exception for flash. 1245 base::ListValue disabled_plugins_exceptions; 1246 disabled_plugins_exceptions.Append( 1247 base::Value::CreateStringValue("*Flash*")); 1248 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY, 1249 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL); 1250 UpdateProviderPolicy(policies); 1251 // It should revert to the user's preference automatically. 1252 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1253 // And the user should be able to disable and enable again. 1254 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 1255 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1256 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true)); 1257 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1258 } 1259 1260 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) { 1261 // Verifies that a plugin can be force-installed with a policy. 1262 std::vector<content::WebPluginInfo> plugins; 1263 GetPluginList(&plugins); 1264 const content::WebPluginInfo* flash = GetFlashPlugin(plugins); 1265 if (!flash) 1266 return; 1267 PluginPrefs* plugin_prefs = 1268 PluginPrefs::GetForProfile(browser()->profile()).get(); 1269 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1270 1271 // The user disables it and then a policy forces it to be enabled. 1272 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 1273 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1274 base::ListValue plugin_list; 1275 plugin_list.Append(base::Value::CreateStringValue(content::kFlashPluginName)); 1276 PolicyMap policies; 1277 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY, 1278 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL); 1279 UpdateProviderPolicy(policies); 1280 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1281 // The user can't disable it anymore. 1282 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false)); 1283 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1284 1285 // When a plugin is both enabled and disabled, the whitelist takes precedence. 1286 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 1287 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL); 1288 UpdateProviderPolicy(policies); 1289 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1290 } 1291 1292 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) { 1293 // Verifies that dangerous plugins can be always authorized to run with 1294 // a policy. 1295 1296 // Verify that the test page exists. It is only present in checkouts with 1297 // src-internal. 1298 if (!base::PathExists(ui_test_utils::GetTestFilePath( 1299 base::FilePath(FILE_PATH_LITERAL("plugin")), 1300 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) { 1301 LOG(INFO) << 1302 "Test skipped because plugin/quicktime.html test file wasn't found."; 1303 return; 1304 } 1305 1306 ServeContentTestData(); 1307 // No plugins at startup. 1308 EXPECT_EQ(0, CountPlugins()); 1309 1310 content::WebContents* contents = 1311 browser()->tab_strip_model()->GetActiveWebContents(); 1312 ASSERT_TRUE(contents); 1313 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents); 1314 ASSERT_TRUE(infobar_service); 1315 EXPECT_EQ(0u, infobar_service->infobar_count()); 1316 1317 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html")); 1318 GURL url(URLRequestMockHTTPJob::GetMockUrl(path)); 1319 ui_test_utils::NavigateToURL(browser(), url); 1320 // This should have triggered the dangerous plugin infobar. 1321 ASSERT_EQ(1u, infobar_service->infobar_count()); 1322 EXPECT_TRUE( 1323 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate()); 1324 // And the plugin isn't running. 1325 EXPECT_EQ(0, CountPlugins()); 1326 1327 // Now set a policy to always authorize this. 1328 PolicyMap policies; 1329 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY, 1330 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1331 UpdateProviderPolicy(policies); 1332 // Reloading the page shouldn't trigger the infobar this time. 1333 ui_test_utils::NavigateToURL(browser(), url); 1334 EXPECT_EQ(0u, infobar_service->infobar_count()); 1335 // And the plugin started automatically. 1336 EXPECT_EQ(1, CountPlugins()); 1337 } 1338 1339 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) { 1340 // Verifies that access to the developer tools can be disabled. 1341 1342 // Open devtools. 1343 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS)); 1344 content::WebContents* contents = 1345 browser()->tab_strip_model()->GetActiveWebContents(); 1346 DevToolsWindow *devtools_window = 1347 DevToolsWindow::GetDockedInstanceForInspectedTab(contents); 1348 EXPECT_TRUE(devtools_window); 1349 1350 // Disable devtools via policy. 1351 PolicyMap policies; 1352 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY, 1353 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1354 content::WindowedNotificationObserver close_observer( 1355 content::NOTIFICATION_WEB_CONTENTS_DESTROYED, 1356 content::Source<content::WebContents>(devtools_window->web_contents())); 1357 UpdateProviderPolicy(policies); 1358 // wait for devtools close 1359 close_observer.Wait(); 1360 // The existing devtools window should have closed. 1361 EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents)); 1362 // And it's not possible to open it again. 1363 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS)); 1364 EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents)); 1365 } 1366 1367 // TODO(samarth): remove along with rest of NTP4 code. 1368 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) { 1369 #if defined(OS_WIN) && defined(USE_ASH) 1370 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 1371 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 1372 return; 1373 #endif 1374 1375 // Verifies that the web store icons can be hidden from the new tab page. 1376 1377 // Open new tab page and look for the web store icons. 1378 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 1379 content::WebContents* contents = 1380 browser()->tab_strip_model()->GetActiveWebContents(); 1381 1382 #if !defined(OS_CHROMEOS) 1383 // Look for web store's app ID in the apps page. 1384 EXPECT_TRUE(ContainsVisibleElement(contents, 1385 "ahfgeienlihckogmohjhadlkjgocpleb")); 1386 #endif 1387 1388 // The next NTP has no footer. 1389 if (ContainsVisibleElement(contents, "footer")) 1390 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link")); 1391 1392 // Turn off the web store icons. 1393 PolicyMap policies; 1394 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY, 1395 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1396 UpdateProviderPolicy(policies); 1397 1398 // The web store icons should now be hidden. 1399 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 1400 EXPECT_FALSE(ContainsVisibleElement(contents, 1401 "ahfgeienlihckogmohjhadlkjgocpleb")); 1402 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link")); 1403 } 1404 1405 // This policy isn't available on Chrome OS. 1406 #if !defined(OS_CHROMEOS) 1407 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) { 1408 // Verifies that the download directory can be forced by policy. 1409 1410 // Set the initial download directory. 1411 base::ScopedTempDir initial_dir; 1412 ASSERT_TRUE(initial_dir.CreateUniqueTempDir()); 1413 browser()->profile()->GetPrefs()->SetFilePath( 1414 prefs::kDownloadDefaultDirectory, initial_dir.path()); 1415 // Don't prompt for the download location during this test. 1416 browser()->profile()->GetPrefs()->SetBoolean( 1417 prefs::kPromptForDownload, false); 1418 1419 // Verify that downloads end up on the default directory. 1420 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1421 DownloadAndVerifyFile(browser(), initial_dir.path(), file); 1422 file_util::DieFileDie(initial_dir.path().Append(file), false); 1423 1424 // Override the download directory with the policy and verify a download. 1425 base::ScopedTempDir forced_dir; 1426 ASSERT_TRUE(forced_dir.CreateUniqueTempDir()); 1427 PolicyMap policies; 1428 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY, 1429 POLICY_SCOPE_USER, 1430 base::Value::CreateStringValue(forced_dir.path().value()), NULL); 1431 UpdateProviderPolicy(policies); 1432 DownloadAndVerifyFile(browser(), forced_dir.path(), file); 1433 // Verify that the first download location wasn't affected. 1434 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file))); 1435 } 1436 #endif 1437 1438 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) { 1439 // Verifies that blacklisted extensions can't be installed. 1440 ExtensionService* service = extension_service(); 1441 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1442 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1443 base::ListValue blacklist; 1444 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId)); 1445 PolicyMap policies; 1446 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1447 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1448 UpdateProviderPolicy(policies); 1449 1450 // "good.crx" is blacklisted. 1451 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1452 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1453 1454 // "adblock.crx" is not. 1455 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName); 1456 ASSERT_TRUE(adblock); 1457 EXPECT_EQ(kAdBlockCrxId, adblock->id()); 1458 EXPECT_EQ(adblock, 1459 service->GetExtensionById(kAdBlockCrxId, true)); 1460 } 1461 1462 // Flaky on windows; http://crbug.com/307994. 1463 #if defined(OS_WIN) 1464 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard 1465 #else 1466 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard 1467 #endif 1468 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) { 1469 // Verify that a wildcard blacklist takes effect. 1470 EXPECT_TRUE(InstallExtension(kAdBlockCrxName)); 1471 ExtensionService* service = extension_service(); 1472 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1473 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true)); 1474 base::ListValue blacklist; 1475 blacklist.Append(base::Value::CreateStringValue("*")); 1476 PolicyMap policies; 1477 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1478 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1479 UpdateProviderPolicy(policies); 1480 1481 // AdBlock was automatically removed. 1482 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1483 1484 // And can't be installed again, nor can good.crx. 1485 EXPECT_FALSE(InstallExtension(kAdBlockCrxName)); 1486 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1487 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1488 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1489 } 1490 1491 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) { 1492 // Verifies that the whitelist can open exceptions to the blacklist. 1493 ExtensionService* service = extension_service(); 1494 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1495 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1496 base::ListValue blacklist; 1497 blacklist.Append(base::Value::CreateStringValue("*")); 1498 base::ListValue whitelist; 1499 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId)); 1500 PolicyMap policies; 1501 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1502 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1503 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY, 1504 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL); 1505 UpdateProviderPolicy(policies); 1506 // "adblock.crx" is blacklisted. 1507 EXPECT_FALSE(InstallExtension(kAdBlockCrxName)); 1508 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1509 // "good.crx" has a whitelist exception. 1510 const extensions::Extension* good = InstallExtension(kGoodCrxName); 1511 ASSERT_TRUE(good); 1512 EXPECT_EQ(kGoodCrxId, good->id()); 1513 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true)); 1514 // The user can also remove this extension. 1515 UninstallExtension(kGoodCrxId, true); 1516 } 1517 1518 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) { 1519 // Verifies that extensions that are force-installed by policies are 1520 // installed and can't be uninstalled. 1521 ExtensionService* service = extension_service(); 1522 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1523 1524 // Extensions that are force-installed come from an update URL, which defaults 1525 // to the webstore. Use a mock URL for this test with an update manifest 1526 // that includes "good_v1.crx". 1527 base::FilePath path = 1528 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName); 1529 GURL url(URLRequestMockHTTPJob::GetMockUrl(path)); 1530 1531 // Setting the forcelist extension should install "good_v1.crx". 1532 base::ListValue forcelist; 1533 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf( 1534 "%s;%s", kGoodCrxId, url.spec().c_str()))); 1535 PolicyMap policies; 1536 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY, 1537 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL); 1538 content::WindowedNotificationObserver observer( 1539 chrome::NOTIFICATION_EXTENSION_INSTALLED, 1540 content::NotificationService::AllSources()); 1541 UpdateProviderPolicy(policies); 1542 observer.Wait(); 1543 // Note: Cannot check that the notification details match the expected 1544 // exception, since the details object has already been freed prior to 1545 // the completion of observer.Wait(). 1546 1547 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true)); 1548 1549 // The user is not allowed to uninstall force-installed extensions. 1550 UninstallExtension(kGoodCrxId, false); 1551 1552 // The user is not allowed to load an unpacked extension with the 1553 // same ID as a force-installed extension. 1554 LoadUnpackedExtension(kGoodUnpackedExt, false); 1555 1556 // Loading other unpacked extensions are not blocked. 1557 LoadUnpackedExtension(kAppUnpackedExt, true); 1558 1559 const std::string old_version_number = 1560 service->GetExtensionById(kGoodCrxId, true)->version()->GetString(); 1561 1562 base::FilePath test_path; 1563 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path)); 1564 1565 TestRequestInterceptor interceptor( 1566 "update.extension", 1567 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)); 1568 interceptor.PushJobCallback( 1569 TestRequestInterceptor::FileJob( 1570 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName))); 1571 1572 // Updating the force-installed extension. 1573 extensions::ExtensionUpdater* updater = service->updater(); 1574 extensions::ExtensionUpdater::CheckParams params; 1575 params.install_immediately = true; 1576 content::WindowedNotificationObserver update_observer( 1577 chrome::NOTIFICATION_EXTENSION_INSTALLED, 1578 content::NotificationService::AllSources()); 1579 updater->CheckNow(params); 1580 update_observer.Wait(); 1581 1582 const base::Version* new_version = 1583 service->GetExtensionById(kGoodCrxId, true)->version(); 1584 ASSERT_TRUE(new_version->IsValid()); 1585 base::Version old_version(old_version_number); 1586 ASSERT_TRUE(old_version.IsValid()); 1587 1588 EXPECT_EQ(1, new_version->CompareTo(old_version)); 1589 1590 EXPECT_EQ(0u, interceptor.GetPendingSize()); 1591 1592 // Wait until any background pages belonging to force-installed extensions 1593 // have been loaded. 1594 extensions::ProcessManager* manager = 1595 extensions::ExtensionSystem::Get(browser()->profile())->process_manager(); 1596 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews(); 1597 for (extensions::ProcessManager::ViewSet::const_iterator iter = 1598 all_views.begin(); 1599 iter != all_views.end();) { 1600 if (!(*iter)->IsLoading()) { 1601 ++iter; 1602 } else { 1603 content::WebContents* web_contents = 1604 content::WebContents::FromRenderViewHost(*iter); 1605 ASSERT_TRUE(web_contents); 1606 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait(); 1607 1608 // Test activity may have modified the set of extension processes during 1609 // message processing, so re-start the iteration to catch added/removed 1610 // processes. 1611 all_views = manager->GetAllViews(); 1612 iter = all_views.begin(); 1613 } 1614 } 1615 1616 // Test policy-installed extensions are reloaded when killed. 1617 BackgroundContentsService:: 1618 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0); 1619 content::WindowedNotificationObserver extension_crashed_observer( 1620 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, 1621 content::NotificationService::AllSources()); 1622 content::WindowedNotificationObserver extension_loaded_observer( 1623 chrome::NOTIFICATION_EXTENSION_LOADED, 1624 content::NotificationService::AllSources()); 1625 extensions::ExtensionHost* extension_host = 1626 extensions::ExtensionSystem::Get(browser()->profile())-> 1627 process_manager()->GetBackgroundHostForExtension(kGoodCrxId); 1628 base::KillProcess(extension_host->render_process_host()->GetHandle(), 1629 content::RESULT_CODE_KILLED, false); 1630 extension_crashed_observer.Wait(); 1631 extension_loaded_observer.Wait(); 1632 } 1633 1634 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) { 1635 // Verifies that extensions are blocked if policy specifies an allowed types 1636 // list and the extension's type is not on that list. 1637 ExtensionService* service = extension_service(); 1638 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1639 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true)); 1640 1641 base::ListValue allowed_types; 1642 allowed_types.AppendString("hosted_app"); 1643 PolicyMap policies; 1644 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY, 1645 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL); 1646 UpdateProviderPolicy(policies); 1647 1648 // "good.crx" is blocked. 1649 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1650 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1651 1652 // "hosted_app.crx" is of a whitelisted type. 1653 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName); 1654 ASSERT_TRUE(hosted_app); 1655 EXPECT_EQ(kHostedAppCrxId, hosted_app->id()); 1656 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true)); 1657 1658 // The user can remove the extension. 1659 UninstallExtension(kHostedAppCrxId, true); 1660 } 1661 1662 // Checks that a click on an extension CRX download triggers the extension 1663 // installation prompt without further user interaction when the source is 1664 // whitelisted by policy. 1665 // Flaky on windows; http://crbug.com/295729 . 1666 #if defined(OS_WIN) 1667 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources 1668 #else 1669 #define MAYBE_ExtensionInstallSources ExtensionInstallSources 1670 #endif 1671 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) { 1672 CommandLine::ForCurrentProcess()->AppendSwitchASCII( 1673 switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); 1674 1675 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl( 1676 base::FilePath(FILE_PATH_LITERAL("extensions/*")))); 1677 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl( 1678 base::FilePath(FILE_PATH_LITERAL("policy/*")))); 1679 1680 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath( 1681 FILE_PATH_LITERAL("policy/extension_install_sources_test.html")))); 1682 ui_test_utils::NavigateToURL(browser(), download_page_url); 1683 1684 // As long as the policy is not present, extensions are considered dangerous. 1685 content::DownloadTestObserverTerminal download_observer( 1686 content::BrowserContext::GetDownloadManager(browser()->profile()), 1, 1687 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY); 1688 PerformClick(0, 0); 1689 download_observer.WaitForFinished(); 1690 1691 // Install the policy and trigger another download. 1692 base::ListValue install_sources; 1693 install_sources.AppendString(install_source_url.spec()); 1694 install_sources.AppendString(referrer_url.spec()); 1695 PolicyMap policies; 1696 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY, 1697 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL); 1698 UpdateProviderPolicy(policies); 1699 1700 content::WindowedNotificationObserver observer( 1701 chrome::NOTIFICATION_EXTENSION_INSTALLED, 1702 content::NotificationService::AllSources()); 1703 PerformClick(1, 0); 1704 observer.Wait(); 1705 // Note: Cannot check that the notification details match the expected 1706 // exception, since the details object has already been freed prior to 1707 // the completion of observer.Wait(). 1708 1709 // The first extension shouldn't be present, the second should be there. 1710 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true)); 1711 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false)); 1712 } 1713 1714 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) { 1715 #if defined(OS_WIN) && defined(USE_ASH) 1716 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 1717 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 1718 return; 1719 #endif 1720 1721 // Verifies that the homepage can be configured with policies. 1722 // Set a default, and check that the home button navigates there. 1723 browser()->profile()->GetPrefs()->SetString( 1724 prefs::kHomePage, chrome::kChromeUIPolicyURL); 1725 browser()->profile()->GetPrefs()->SetBoolean( 1726 prefs::kHomePageIsNewTabPage, false); 1727 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), 1728 browser()->profile()->GetHomePage()); 1729 content::WebContents* contents = 1730 browser()->tab_strip_model()->GetActiveWebContents(); 1731 EXPECT_EQ(GURL(content::kAboutBlankURL), contents->GetURL()); 1732 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1733 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL()); 1734 1735 // Now override with policy. 1736 PolicyMap policies; 1737 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY, 1738 POLICY_SCOPE_USER, 1739 base::Value::CreateStringValue(chrome::kChromeUICreditsURL), 1740 NULL); 1741 UpdateProviderPolicy(policies); 1742 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1743 content::WaitForLoadStop(contents); 1744 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL()); 1745 1746 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, 1747 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1748 UpdateProviderPolicy(policies); 1749 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1750 content::WaitForLoadStop(contents); 1751 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL()); 1752 } 1753 1754 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) { 1755 // Verifies that incognito windows can't be opened when disabled by policy. 1756 1757 const BrowserList* active_browser_list = 1758 BrowserList::GetInstance(chrome::GetActiveDesktop()); 1759 1760 // Disable incognito via policy and verify that incognito windows can't be 1761 // opened. 1762 EXPECT_EQ(1u, active_browser_list->size()); 1763 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive()); 1764 PolicyMap policies; 1765 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY, 1766 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1767 UpdateProviderPolicy(policies); 1768 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW)); 1769 EXPECT_EQ(1u, active_browser_list->size()); 1770 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive()); 1771 1772 // Enable via policy and verify that incognito windows can be opened. 1773 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY, 1774 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1775 UpdateProviderPolicy(policies); 1776 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW)); 1777 EXPECT_EQ(2u, active_browser_list->size()); 1778 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive()); 1779 } 1780 1781 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) { 1782 // Verifies that Javascript can be disabled. 1783 content::WebContents* contents = 1784 browser()->tab_strip_model()->GetActiveWebContents(); 1785 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1786 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS)); 1787 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE)); 1788 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES)); 1789 1790 // Disable Javascript via policy. 1791 PolicyMap policies; 1792 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY, 1793 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1794 UpdateProviderPolicy(policies); 1795 // Reload the page. 1796 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL)); 1797 EXPECT_FALSE(IsJavascriptEnabled(contents)); 1798 // Developer tools still work when javascript is disabled. 1799 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS)); 1800 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE)); 1801 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES)); 1802 // Javascript is always enabled for the internal pages. 1803 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL)); 1804 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1805 1806 // The javascript content setting policy overrides the javascript policy. 1807 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL)); 1808 EXPECT_FALSE(IsJavascriptEnabled(contents)); 1809 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY, 1810 POLICY_SCOPE_USER, 1811 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL); 1812 UpdateProviderPolicy(policies); 1813 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL)); 1814 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1815 } 1816 1817 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) { 1818 // Verifies that browsing history is not saved. 1819 PolicyMap policies; 1820 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY, 1821 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1822 UpdateProviderPolicy(policies); 1823 GURL url = ui_test_utils::GetTestUrl( 1824 base::FilePath(base::FilePath::kCurrentDirectory), 1825 base::FilePath(FILE_PATH_LITERAL("empty.html"))); 1826 ui_test_utils::NavigateToURL(browser(), url); 1827 // Verify that the navigation wasn't saved in the history. 1828 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile()); 1829 EXPECT_EQ(0u, enumerator1.urls().size()); 1830 1831 // Now flip the policy and try again. 1832 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY, 1833 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1834 UpdateProviderPolicy(policies); 1835 ui_test_utils::NavigateToURL(browser(), url); 1836 // Verify that the navigation was saved in the history. 1837 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile()); 1838 ASSERT_EQ(1u, enumerator2.urls().size()); 1839 EXPECT_EQ(url, enumerator2.urls()[0]); 1840 } 1841 1842 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly. 1843 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) { 1844 // Verifies that translate can be forced enabled or disabled by policy. 1845 1846 // Get the InfoBarService, and verify that there are no infobars on startup. 1847 content::WebContents* contents = 1848 browser()->tab_strip_model()->GetActiveWebContents(); 1849 ASSERT_TRUE(contents); 1850 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents); 1851 ASSERT_TRUE(infobar_service); 1852 EXPECT_EQ(0u, infobar_service->infobar_count()); 1853 1854 // Force enable the translate feature. 1855 PolicyMap policies; 1856 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY, 1857 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 1858 UpdateProviderPolicy(policies); 1859 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test 1860 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the 1861 // TranslateManager observes. This allows checking that an infobar is NOT 1862 // shown below, without polling for infobars for some indeterminate amount 1863 // of time. 1864 GURL url = ui_test_utils::GetTestUrl( 1865 base::FilePath(), 1866 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html"))); 1867 content::WindowedNotificationObserver language_observer1( 1868 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, 1869 content::NotificationService::AllSources()); 1870 ui_test_utils::NavigateToURL(browser(), url); 1871 language_observer1.Wait(); 1872 1873 // Verify the translation detected for this tab. 1874 TranslateTabHelper* translate_tab_helper = 1875 TranslateTabHelper::FromWebContents(contents); 1876 ASSERT_TRUE(translate_tab_helper); 1877 LanguageState& language_state = translate_tab_helper->language_state(); 1878 EXPECT_EQ("fr", language_state.original_language()); 1879 EXPECT_TRUE(language_state.page_needs_translation()); 1880 EXPECT_FALSE(language_state.translation_pending()); 1881 EXPECT_FALSE(language_state.translation_declined()); 1882 EXPECT_FALSE(language_state.IsPageTranslated()); 1883 1884 // Verify that the translate infobar showed up. 1885 ASSERT_EQ(1u, infobar_service->infobar_count()); 1886 InfoBar* infobar = infobar_service->infobar_at(0); 1887 TranslateInfoBarDelegate* translate_infobar_delegate = 1888 infobar->delegate()->AsTranslateInfoBarDelegate(); 1889 ASSERT_TRUE(translate_infobar_delegate); 1890 EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE, 1891 translate_infobar_delegate->infobar_type()); 1892 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code()); 1893 1894 // Now force disable translate. 1895 infobar_service->RemoveInfoBar(infobar); 1896 EXPECT_EQ(0u, infobar_service->infobar_count()); 1897 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY, 1898 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 1899 UpdateProviderPolicy(policies); 1900 // Navigating to the same URL now doesn't trigger an infobar. 1901 content::WindowedNotificationObserver language_observer2( 1902 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, 1903 content::NotificationService::AllSources()); 1904 ui_test_utils::NavigateToURL(browser(), url); 1905 language_observer2.Wait(); 1906 EXPECT_EQ(0u, infobar_service->infobar_count()); 1907 } 1908 1909 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) { 1910 // Checks that URLs can be blacklisted, and that exceptions can be made to 1911 // the blacklist. 1912 1913 // Filter |kURLS| on IO thread, so that requests to those hosts end up 1914 // as URLRequestMockHTTPJobs. 1915 const char* kURLS[] = { 1916 "http://aaa.com/empty.html", 1917 "http://bbb.com/empty.html", 1918 "http://sub.bbb.com/empty.html", 1919 "http://bbb.com/policy/blank.html", 1920 }; 1921 { 1922 base::RunLoop loop; 1923 BrowserThread::PostTaskAndReply( 1924 BrowserThread::IO, FROM_HERE, 1925 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)), 1926 loop.QuitClosure()); 1927 loop.Run(); 1928 } 1929 1930 // Verify that "bbb.com" opens before applying the blacklist. 1931 CheckCanOpenURL(browser(), kURLS[1]); 1932 1933 // Set a blacklist. 1934 base::ListValue blacklist; 1935 blacklist.Append(base::Value::CreateStringValue("bbb.com")); 1936 PolicyMap policies; 1937 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, 1938 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1939 UpdateProviderPolicy(policies); 1940 FlushBlacklistPolicy(); 1941 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked. 1942 CheckCanOpenURL(browser(), kURLS[0]); 1943 for (size_t i = 1; i < arraysize(kURLS); ++i) 1944 CheckURLIsBlocked(browser(), kURLS[i]); 1945 1946 // Whitelist some sites of bbb.com. 1947 base::ListValue whitelist; 1948 whitelist.Append(base::Value::CreateStringValue("sub.bbb.com")); 1949 whitelist.Append(base::Value::CreateStringValue("bbb.com/policy")); 1950 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, 1951 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL); 1952 UpdateProviderPolicy(policies); 1953 FlushBlacklistPolicy(); 1954 CheckURLIsBlocked(browser(), kURLS[1]); 1955 CheckCanOpenURL(browser(), kURLS[2]); 1956 CheckCanOpenURL(browser(), kURLS[3]); 1957 1958 { 1959 base::RunLoop loop; 1960 BrowserThread::PostTaskAndReply( 1961 BrowserThread::IO, FROM_HERE, 1962 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)), 1963 loop.QuitClosure()); 1964 loop.Run(); 1965 } 1966 } 1967 1968 IN_PROC_BROWSER_TEST_F(PolicyTest, FileURLBlacklist) { 1969 // Check that FileURLs can be blacklisted and DisabledSchemes works together 1970 // with URLblacklisting and URLwhitelisting. 1971 1972 base::FilePath test_path; 1973 PathService::Get(chrome::DIR_TEST_DATA, &test_path); 1974 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/"; 1975 const std::string folder_path = base_path + "apptest/"; 1976 const std::string file_path1 = base_path + "title1.html"; 1977 const std::string file_path2 = folder_path + "basic.html"; 1978 1979 CheckCanOpenURL(browser(), file_path1.c_str()); 1980 CheckCanOpenURL(browser(), file_path2.c_str()); 1981 1982 // Set a blacklist for all the files. 1983 base::ListValue blacklist; 1984 blacklist.Append(base::Value::CreateStringValue("file://*")); 1985 PolicyMap policies; 1986 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, 1987 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1988 UpdateProviderPolicy(policies); 1989 FlushBlacklistPolicy(); 1990 1991 CheckURLIsBlocked(browser(), file_path1.c_str()); 1992 CheckURLIsBlocked(browser(), file_path2.c_str()); 1993 1994 // Replace the URLblacklist with disabling the file scheme. 1995 blacklist.Remove(base::StringValue("file://*"), NULL); 1996 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, 1997 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 1998 UpdateProviderPolicy(policies); 1999 FlushBlacklistPolicy(); 2000 2001 PrefService* prefs = browser()->profile()->GetPrefs(); 2002 const base::ListValue* list_url = prefs->GetList(prefs::kUrlBlacklist); 2003 EXPECT_EQ(list_url->Find(base::StringValue("file://*")), 2004 list_url->end()); 2005 2006 base::ListValue disabledscheme; 2007 disabledscheme.Append(base::Value::CreateStringValue("file")); 2008 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY, 2009 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL); 2010 UpdateProviderPolicy(policies); 2011 FlushBlacklistPolicy(); 2012 2013 list_url = prefs->GetList(prefs::kUrlBlacklist); 2014 EXPECT_NE(list_url->Find(base::StringValue("file://*")), 2015 list_url->end()); 2016 2017 // Whitelist one folder and blacklist an another just inside. 2018 base::ListValue whitelist; 2019 whitelist.Append(base::Value::CreateStringValue(base_path)); 2020 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, 2021 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL); 2022 blacklist.Append(base::Value::CreateStringValue(folder_path)); 2023 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, 2024 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL); 2025 UpdateProviderPolicy(policies); 2026 FlushBlacklistPolicy(); 2027 2028 CheckCanOpenURL(browser(), file_path1.c_str()); 2029 CheckURLIsBlocked(browser(), file_path2.c_str()); 2030 } 2031 2032 #if !defined(OS_MACOSX) 2033 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) { 2034 PolicyMap policies; 2035 policies.Set(key::kFullscreenAllowed, 2036 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2037 base::Value::CreateBooleanValue(false), NULL); 2038 UpdateProviderPolicy(policies); 2039 2040 BrowserWindow* browser_window = browser()->window(); 2041 ASSERT_TRUE(browser_window); 2042 2043 EXPECT_FALSE(browser_window->IsFullscreen()); 2044 chrome::ToggleFullscreenMode(browser()); 2045 EXPECT_FALSE(browser_window->IsFullscreen()); 2046 } 2047 2048 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) { 2049 PolicyMap policies; 2050 policies.Set(key::kFullscreenAllowed, 2051 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2052 base::Value::CreateBooleanValue(false), NULL); 2053 UpdateProviderPolicy(policies); 2054 2055 const extensions::Extension* extension = 2056 LoadUnpackedExtension(kUnpackedFullscreenAppName, true); 2057 ASSERT_TRUE(extension); 2058 2059 // Launch an app that tries to open a fullscreen window. 2060 TestAddShellWindowObserver add_window_observer( 2061 apps::ShellWindowRegistry::Get(browser()->profile())); 2062 OpenApplication(AppLaunchParams(browser()->profile(), 2063 extension, 2064 extensions::LAUNCH_CONTAINER_NONE, 2065 NEW_WINDOW)); 2066 apps::ShellWindow* window = add_window_observer.WaitForShellWindow(); 2067 ASSERT_TRUE(window); 2068 2069 // Verify that the window is not in fullscreen mode. 2070 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen()); 2071 2072 // Verify that the window cannot be toggled into fullscreen mode via apps 2073 // APIs. 2074 EXPECT_TRUE(content::ExecuteScript( 2075 window->web_contents(), 2076 "chrome.app.window.current().fullscreen();")); 2077 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen()); 2078 2079 // Verify that the window cannot be toggled into fullscreen mode from within 2080 // Chrome (e.g., using keyboard accelerators). 2081 window->Fullscreen(); 2082 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen()); 2083 } 2084 #endif 2085 2086 #if defined(OS_CHROMEOS) 2087 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) { 2088 int screenshot_count = CountScreenshots(); 2089 2090 // Make sure screenshots are counted correctly. 2091 TestScreenshotFile(true); 2092 ASSERT_EQ(CountScreenshots(), screenshot_count + 1); 2093 2094 // Check if trying to take a screenshot fails when disabled by policy. 2095 TestScreenshotFile(false); 2096 ASSERT_EQ(CountScreenshots(), screenshot_count + 1); 2097 } 2098 2099 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) { 2100 // Set up the mock observer. 2101 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get(); 2102 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver); 2103 audio_handler->AddAudioObserver(test_observer.get()); 2104 2105 bool prior_state = audio_handler->IsOutputMuted(); 2106 // Make sure the audio is not muted and then toggle the policy and observe 2107 // if the output mute changed event is fired. 2108 audio_handler->SetOutputMute(false); 2109 EXPECT_FALSE(audio_handler->IsOutputMuted()); 2110 EXPECT_EQ(1, test_observer->output_mute_changed_count()); 2111 PolicyMap policies; 2112 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY, 2113 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL); 2114 UpdateProviderPolicy(policies); 2115 EXPECT_TRUE(audio_handler->IsOutputMuted()); 2116 // This should not change the state now and should not trigger output mute 2117 // changed event. 2118 audio_handler->SetOutputMute(false); 2119 EXPECT_TRUE(audio_handler->IsOutputMuted()); 2120 EXPECT_EQ(1, test_observer->output_mute_changed_count()); 2121 2122 // Toggle back and observe if the output mute changed event is fired. 2123 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY, 2124 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL); 2125 UpdateProviderPolicy(policies); 2126 EXPECT_FALSE(audio_handler->IsOutputMuted()); 2127 EXPECT_EQ(1, test_observer->output_mute_changed_count()); 2128 audio_handler->SetOutputMute(true); 2129 EXPECT_TRUE(audio_handler->IsOutputMuted()); 2130 EXPECT_EQ(2, test_observer->output_mute_changed_count()); 2131 // Revert the prior state. 2132 audio_handler->SetOutputMute(prior_state); 2133 audio_handler->RemoveAudioObserver(test_observer.get()); 2134 } 2135 2136 // Disabled, see http://crbug.com/315308. 2137 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) { 2138 // Indicate that the session started 2 hours ago and no user activity has 2139 // occurred yet. 2140 g_browser_process->local_state()->SetInt64( 2141 prefs::kSessionStartTime, 2142 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2)) 2143 .ToInternalValue()); 2144 } 2145 2146 // Disabled, see http://crbug.com/315308. 2147 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) { 2148 content::MockNotificationObserver observer; 2149 content::NotificationRegistrar registrar; 2150 registrar.Add(&observer, 2151 chrome::NOTIFICATION_APP_TERMINATING, 2152 content::NotificationService::AllSources()); 2153 2154 // Set the session length limit to 3 hours. Verify that the session is not 2155 // terminated. 2156 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)) 2157 .Times(0); 2158 PolicyMap policies; 2159 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 2160 POLICY_SCOPE_USER, 2161 base::Value::CreateIntegerValue(kThreeHoursInMs), 2162 NULL); 2163 UpdateProviderPolicy(policies); 2164 base::RunLoop().RunUntilIdle(); 2165 Mock::VerifyAndClearExpectations(&observer); 2166 2167 // Decrease the session length limit to 1 hour. Verify that the session is 2168 // terminated immediately. 2169 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)); 2170 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 2171 POLICY_SCOPE_USER, 2172 base::Value::CreateIntegerValue(kOneHourInMs), 2173 NULL); 2174 UpdateProviderPolicy(policies); 2175 base::RunLoop().RunUntilIdle(); 2176 Mock::VerifyAndClearExpectations(&observer); 2177 } 2178 2179 // Disabled, see http://crbug.com/315308. 2180 IN_PROC_BROWSER_TEST_F(PolicyTest, 2181 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) { 2182 // Indicate that the session started 2 hours ago and no user activity has 2183 // occurred yet. 2184 g_browser_process->local_state()->SetInt64( 2185 prefs::kSessionStartTime, 2186 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2)) 2187 .ToInternalValue()); 2188 } 2189 2190 // Disabled, see http://crbug.com/315308. 2191 IN_PROC_BROWSER_TEST_F(PolicyTest, 2192 DISABLED_WaitForInitialUserActivityUsatisfied) { 2193 content::MockNotificationObserver observer; 2194 content::NotificationRegistrar registrar; 2195 registrar.Add(&observer, 2196 chrome::NOTIFICATION_APP_TERMINATING, 2197 content::NotificationService::AllSources()); 2198 2199 // Require initial user activity. 2200 PolicyMap policies; 2201 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY, 2202 POLICY_SCOPE_USER, 2203 new base::FundamentalValue(true), 2204 NULL); 2205 UpdateProviderPolicy(policies); 2206 base::RunLoop().RunUntilIdle(); 2207 2208 // Set the session length limit to 1 hour. Verify that the session is not 2209 // terminated. 2210 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)) 2211 .Times(0); 2212 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 2213 POLICY_SCOPE_USER, 2214 base::Value::CreateIntegerValue(kOneHourInMs), 2215 NULL); 2216 UpdateProviderPolicy(policies); 2217 base::RunLoop().RunUntilIdle(); 2218 Mock::VerifyAndClearExpectations(&observer); 2219 } 2220 2221 // Disabled, see http://crbug.com/315308. 2222 IN_PROC_BROWSER_TEST_F(PolicyTest, 2223 DISABLED_PRE_WaitForInitialUserActivitySatisfied) { 2224 // Indicate that initial user activity in this session occurred 2 hours ago. 2225 g_browser_process->local_state()->SetInt64( 2226 prefs::kSessionStartTime, 2227 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2)) 2228 .ToInternalValue()); 2229 g_browser_process->local_state()->SetBoolean( 2230 prefs::kSessionUserActivitySeen, 2231 true); 2232 } 2233 2234 // Disabled, see http://crbug.com/315308. 2235 IN_PROC_BROWSER_TEST_F(PolicyTest, 2236 DISABLED_WaitForInitialUserActivitySatisfied) { 2237 content::MockNotificationObserver observer; 2238 content::NotificationRegistrar registrar; 2239 registrar.Add(&observer, 2240 chrome::NOTIFICATION_APP_TERMINATING, 2241 content::NotificationService::AllSources()); 2242 2243 // Require initial user activity and set the session length limit to 3 hours. 2244 // Verify that the session is not terminated. 2245 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)) 2246 .Times(0); 2247 PolicyMap policies; 2248 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY, 2249 POLICY_SCOPE_USER, 2250 new base::FundamentalValue(true), 2251 NULL); 2252 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 2253 POLICY_SCOPE_USER, 2254 base::Value::CreateIntegerValue(kThreeHoursInMs), 2255 NULL); 2256 UpdateProviderPolicy(policies); 2257 base::RunLoop().RunUntilIdle(); 2258 Mock::VerifyAndClearExpectations(&observer); 2259 2260 // Decrease the session length limit to 1 hour. Verify that the session is 2261 // terminated immediately. 2262 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)); 2263 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 2264 POLICY_SCOPE_USER, 2265 base::Value::CreateIntegerValue(kOneHourInMs), 2266 NULL); 2267 UpdateProviderPolicy(policies); 2268 base::RunLoop().RunUntilIdle(); 2269 Mock::VerifyAndClearExpectations(&observer); 2270 } 2271 2272 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) { 2273 // Verifies that the large cursor accessibility feature can be controlled 2274 // through policy. 2275 chromeos::AccessibilityManager* accessibility_manager = 2276 chromeos::AccessibilityManager::Get(); 2277 2278 // Manually enable the large cursor. 2279 accessibility_manager->EnableLargeCursor(true); 2280 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled()); 2281 2282 // Verify that policy overrides the manual setting. 2283 PolicyMap policies; 2284 policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY, 2285 POLICY_SCOPE_USER, 2286 base::Value::CreateBooleanValue(false), NULL); 2287 UpdateProviderPolicy(policies); 2288 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled()); 2289 2290 // Verify that the large cursor cannot be enabled manually anymore. 2291 accessibility_manager->EnableLargeCursor(true); 2292 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled()); 2293 } 2294 2295 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) { 2296 // Verifies that the spoken feedback accessibility feature can be controlled 2297 // through policy. 2298 chromeos::AccessibilityManager* accessibility_manager = 2299 chromeos::AccessibilityManager::Get(); 2300 2301 // Manually enable spoken feedback. 2302 accessibility_manager->EnableSpokenFeedback( 2303 true, ash::A11Y_NOTIFICATION_NONE); 2304 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled()); 2305 2306 // Verify that policy overrides the manual setting. 2307 PolicyMap policies; 2308 policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY, 2309 POLICY_SCOPE_USER, 2310 base::Value::CreateBooleanValue(false), NULL); 2311 UpdateProviderPolicy(policies); 2312 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled()); 2313 2314 // Verify that spoken feedback cannot be enabled manually anymore. 2315 accessibility_manager->EnableSpokenFeedback( 2316 true, ash::A11Y_NOTIFICATION_NONE); 2317 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled()); 2318 } 2319 2320 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) { 2321 // Verifies that the high contrast mode accessibility feature can be 2322 // controlled through policy. 2323 chromeos::AccessibilityManager* accessibility_manager = 2324 chromeos::AccessibilityManager::Get(); 2325 2326 // Manually enable high contrast mode. 2327 accessibility_manager->EnableHighContrast(true); 2328 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled()); 2329 2330 // Verify that policy overrides the manual setting. 2331 PolicyMap policies; 2332 policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY, 2333 POLICY_SCOPE_USER, 2334 base::Value::CreateBooleanValue(false), NULL); 2335 UpdateProviderPolicy(policies); 2336 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled()); 2337 2338 // Verify that high contrast mode cannot be enabled manually anymore. 2339 accessibility_manager->EnableHighContrast(true); 2340 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled()); 2341 } 2342 2343 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) { 2344 // Verifies that the screen magnifier can be disabled through policy. 2345 chromeos::MagnificationManager* magnification_manager = 2346 chromeos::MagnificationManager::Get(); 2347 2348 // Manually enable the full-screen magnifier. 2349 magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL); 2350 magnification_manager->SetMagnifierEnabled(true); 2351 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType()); 2352 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled()); 2353 2354 // Verify that policy overrides the manual setting. 2355 PolicyMap policies; 2356 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY, 2357 POLICY_SCOPE_USER, 2358 base::Value::CreateIntegerValue(0), NULL); 2359 UpdateProviderPolicy(policies); 2360 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled()); 2361 2362 // Verify that the screen magnifier cannot be enabled manually anymore. 2363 magnification_manager->SetMagnifierEnabled(true); 2364 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled()); 2365 } 2366 2367 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) { 2368 // Verifies that the full-screen magnifier can be enabled through policy. 2369 chromeos::MagnificationManager* magnification_manager = 2370 chromeos::MagnificationManager::Get(); 2371 2372 // Verify that the screen magnifier is initially disabled. 2373 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled()); 2374 2375 // Verify that policy can enable the full-screen magnifier. 2376 PolicyMap policies; 2377 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY, 2378 POLICY_SCOPE_USER, 2379 base::Value::CreateIntegerValue(ash::MAGNIFIER_FULL), NULL); 2380 UpdateProviderPolicy(policies); 2381 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType()); 2382 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled()); 2383 2384 // Verify that the screen magnifier cannot be disabled manually anymore. 2385 magnification_manager->SetMagnifierEnabled(false); 2386 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled()); 2387 } 2388 2389 #endif 2390 2391 namespace { 2392 2393 static const char* kRestoredURLs[] = { 2394 "http://aaa.com/empty.html", 2395 "http://bbb.com/empty.html", 2396 }; 2397 2398 bool IsNonSwitchArgument(const CommandLine::StringType& s) { 2399 return s.empty() || s[0] != '-'; 2400 } 2401 2402 } // namespace 2403 2404 // Similar to PolicyTest but allows setting policies before the browser is 2405 // created. Each test parameter is a method that sets up the early policies 2406 // and stores the expected startup URLs in |expected_urls_|. 2407 class RestoreOnStartupPolicyTest 2408 : public PolicyTest, 2409 public testing::WithParamInterface< 2410 void (RestoreOnStartupPolicyTest::*)(void)> { 2411 public: 2412 RestoreOnStartupPolicyTest() {} 2413 virtual ~RestoreOnStartupPolicyTest() {} 2414 2415 #if defined(OS_CHROMEOS) 2416 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { 2417 // TODO(nkostylev): Investigate if we can remove this switch. 2418 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests); 2419 PolicyTest::SetUpCommandLine(command_line); 2420 } 2421 #endif 2422 2423 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 2424 PolicyTest::SetUpInProcessBrowserTestFixture(); 2425 // Set early policies now, before the browser is created. 2426 (this->*(GetParam()))(); 2427 2428 // Remove the non-switch arguments, so that session restore kicks in for 2429 // these tests. 2430 CommandLine* command_line = CommandLine::ForCurrentProcess(); 2431 CommandLine::StringVector argv = command_line->argv(); 2432 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument), 2433 argv.end()); 2434 command_line->InitFromArgv(argv); 2435 ASSERT_TRUE(std::equal(argv.begin(), argv.end(), 2436 command_line->argv().begin())); 2437 2438 // Redirect the test URLs to the test data directory. 2439 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs)); 2440 } 2441 2442 void HomepageIsNotNTP() { 2443 // Verifies that policy can set the startup pages to the homepage, when 2444 // the homepage is not the NTP. 2445 PolicyMap policies; 2446 policies.Set( 2447 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2448 base::Value::CreateIntegerValue( 2449 SessionStartupPref::kPrefValueHomePage), 2450 NULL); 2451 policies.Set( 2452 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2453 base::Value::CreateBooleanValue(false), NULL); 2454 policies.Set( 2455 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2456 base::Value::CreateStringValue(kRestoredURLs[1]), NULL); 2457 provider_.UpdateChromePolicy(policies); 2458 2459 expected_urls_.push_back(GURL(kRestoredURLs[1])); 2460 } 2461 2462 void HomepageIsNTP() { 2463 // Verifies that policy can set the startup pages to the homepage, when 2464 // the homepage is the NTP. 2465 PolicyMap policies; 2466 policies.Set( 2467 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2468 base::Value::CreateIntegerValue( 2469 SessionStartupPref::kPrefValueHomePage), 2470 NULL); 2471 policies.Set( 2472 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2473 base::Value::CreateBooleanValue(true), NULL); 2474 provider_.UpdateChromePolicy(policies); 2475 2476 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL)); 2477 } 2478 2479 void ListOfURLs() { 2480 // Verifies that policy can set the startup pages to a list of URLs. 2481 base::ListValue urls; 2482 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) { 2483 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i])); 2484 expected_urls_.push_back(GURL(kRestoredURLs[i])); 2485 } 2486 PolicyMap policies; 2487 policies.Set( 2488 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2489 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs), 2490 NULL); 2491 policies.Set( 2492 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2493 urls.DeepCopy(), NULL); 2494 provider_.UpdateChromePolicy(policies); 2495 } 2496 2497 void NTP() { 2498 // Verifies that policy can set the startup page to the NTP. 2499 PolicyMap policies; 2500 policies.Set( 2501 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2502 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab), 2503 NULL); 2504 provider_.UpdateChromePolicy(policies); 2505 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL)); 2506 } 2507 2508 void Last() { 2509 // Verifies that policy can set the startup pages to the last session. 2510 PolicyMap policies; 2511 policies.Set( 2512 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2513 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast), 2514 NULL); 2515 provider_.UpdateChromePolicy(policies); 2516 // This should restore the tabs opened at PRE_RunTest below. 2517 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) 2518 expected_urls_.push_back(GURL(kRestoredURLs[i])); 2519 } 2520 2521 std::vector<GURL> expected_urls_; 2522 }; 2523 2524 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) { 2525 // Open some tabs to verify if they are restored after the browser restarts. 2526 // Most policy settings override this, except kPrefValueLast which enforces 2527 // a restore. 2528 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0])); 2529 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) { 2530 content::WindowedNotificationObserver observer( 2531 content::NOTIFICATION_LOAD_STOP, 2532 content::NotificationService::AllSources()); 2533 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]), 2534 content::PAGE_TRANSITION_LINK); 2535 observer.Wait(); 2536 } 2537 } 2538 2539 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) { 2540 #if defined(OS_WIN) && defined(USE_ASH) 2541 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 2542 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 2543 return; 2544 #endif 2545 2546 TabStripModel* model = browser()->tab_strip_model(); 2547 int size = static_cast<int>(expected_urls_.size()); 2548 EXPECT_EQ(size, model->count()); 2549 for (int i = 0; i < size && i < model->count(); ++i) { 2550 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL()); 2551 } 2552 } 2553 2554 INSTANTIATE_TEST_CASE_P( 2555 RestoreOnStartupPolicyTestInstance, 2556 RestoreOnStartupPolicyTest, 2557 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP, 2558 &RestoreOnStartupPolicyTest::HomepageIsNTP, 2559 &RestoreOnStartupPolicyTest::ListOfURLs, 2560 &RestoreOnStartupPolicyTest::NTP, 2561 &RestoreOnStartupPolicyTest::Last)); 2562 2563 // Similar to PolicyTest but sets a couple of policies before the browser is 2564 // started. 2565 class PolicyStatisticsCollectorTest : public PolicyTest { 2566 public: 2567 PolicyStatisticsCollectorTest() {} 2568 virtual ~PolicyStatisticsCollectorTest() {} 2569 2570 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 2571 PolicyTest::SetUpInProcessBrowserTestFixture(); 2572 PolicyMap policies; 2573 policies.Set( 2574 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2575 base::Value::CreateBooleanValue(true), NULL); 2576 policies.Set( 2577 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2578 base::Value::CreateBooleanValue(false), NULL); 2579 policies.Set( 2580 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2581 base::Value::CreateStringValue("http://chromium.org"), NULL); 2582 provider_.UpdateChromePolicy(policies); 2583 } 2584 }; 2585 2586 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) { 2587 // Verifies that policy usage histograms are collected at startup. 2588 2589 // BrowserPolicyConnector::Init() has already been called. Make sure the 2590 // CompleteInitialization() task has executed as well. 2591 content::RunAllPendingInMessageLoop(); 2592 2593 GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) + 2594 std::string(content::kStandardSchemeSeparator) + 2595 std::string(content::kChromeUIHistogramHost)); 2596 ui_test_utils::NavigateToURL(browser(), kAboutHistograms); 2597 content::WebContents* contents = 2598 browser()->tab_strip_model()->GetActiveWebContents(); 2599 std::string text; 2600 ASSERT_TRUE(content::ExecuteScriptAndExtractString( 2601 contents, 2602 "var nodes = document.querySelectorAll('body > pre');" 2603 "var result = '';" 2604 "for (var i = 0; i < nodes.length; ++i) {" 2605 " var text = nodes[i].innerHTML;" 2606 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {" 2607 " result = text;" 2608 " break;" 2609 " }" 2610 "}" 2611 "domAutomationController.send(result);", 2612 &text)); 2613 ASSERT_FALSE(text.empty()); 2614 const std::string kExpectedLabel = 2615 "Histogram: Enterprise.Policies recorded 3 samples"; 2616 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size())); 2617 // HomepageLocation has policy ID 1. 2618 EXPECT_NE(std::string::npos, text.find("<br>1 ---")); 2619 // ShowHomeButton has policy ID 35. 2620 EXPECT_NE(std::string::npos, text.find("<br>35 ---")); 2621 // BookmarkBarEnabled has policy ID 82. 2622 EXPECT_NE(std::string::npos, text.find("<br>82 ---")); 2623 } 2624 2625 class MediaStreamDevicesControllerBrowserTest 2626 : public PolicyTest, 2627 public testing::WithParamInterface<bool> { 2628 public: 2629 MediaStreamDevicesControllerBrowserTest() 2630 : request_url_allowed_via_whitelist_(false) { 2631 policy_value_ = GetParam(); 2632 } 2633 virtual ~MediaStreamDevicesControllerBrowserTest() {} 2634 2635 // Configure a given policy map. 2636 // The |policy_name| is the name of either the audio or video capture allow 2637 // policy and must never be NULL. 2638 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist 2639 // policy is set. If non-NULL, the request_url_ will be set to be non empty 2640 // and the whitelist policy is set to contain either the |allow_rule| (if 2641 // non-NULL) or an "allow all" wildcard. 2642 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name, 2643 const char* whitelist_policy, 2644 const char* allow_rule) { 2645 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 2646 base::Value::CreateBooleanValue(policy_value_), NULL); 2647 2648 if (whitelist_policy) { 2649 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible 2650 // in the media exceptions UI. 2651 // See discussion here: https://codereview.chromium.org/15738004/ 2652 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode); 2653 2654 // Add an entry to the whitelist that allows the specified URL regardless 2655 // of the setting of kAudioCapturedAllowed. 2656 request_url_ = GURL("http://www.example.com/foo"); 2657 base::ListValue* list = new base::ListValue(); 2658 if (allow_rule) { 2659 list->AppendString(allow_rule); 2660 request_url_allowed_via_whitelist_ = true; 2661 } else { 2662 list->AppendString(ContentSettingsPattern::Wildcard().ToString()); 2663 // We should ignore all wildcard entries in the whitelist, so even 2664 // though we've added an entry, it should be ignored and our expectation 2665 // is that the request has not been allowed via the whitelist. 2666 request_url_allowed_via_whitelist_ = false; 2667 } 2668 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY, 2669 POLICY_SCOPE_USER, list, NULL); 2670 } 2671 } 2672 2673 void Accept(const content::MediaStreamDevices& devices, 2674 scoped_ptr<content::MediaStreamUI> ui) { 2675 if (policy_value_ || request_url_allowed_via_whitelist_) { 2676 ASSERT_EQ(1U, devices.size()); 2677 ASSERT_EQ("fake_dev", devices[0].id); 2678 } else { 2679 ASSERT_EQ(0U, devices.size()); 2680 } 2681 } 2682 2683 void FinishAudioTest() { 2684 content::MediaStreamRequest request(0, 0, 0, 2685 request_url_.GetOrigin(), 2686 content::MEDIA_DEVICE_ACCESS, 2687 std::string(), std::string(), 2688 content::MEDIA_DEVICE_AUDIO_CAPTURE, 2689 content::MEDIA_NO_SERVICE); 2690 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam 2691 // and microphone permissions at the same time. 2692 MediaStreamDevicesController controller( 2693 browser()->tab_strip_model()->GetActiveWebContents(), request, 2694 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this)); 2695 controller.Accept(false); 2696 2697 base::MessageLoop::current()->QuitWhenIdle(); 2698 } 2699 2700 void FinishVideoTest() { 2701 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam 2702 // and microphone permissions at the same time. 2703 content::MediaStreamRequest request(0, 0, 0, 2704 request_url_.GetOrigin(), 2705 content::MEDIA_DEVICE_ACCESS, 2706 std::string(), 2707 std::string(), 2708 content::MEDIA_NO_SERVICE, 2709 content::MEDIA_DEVICE_VIDEO_CAPTURE); 2710 MediaStreamDevicesController controller( 2711 browser()->tab_strip_model()->GetActiveWebContents(), request, 2712 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this)); 2713 controller.Accept(false); 2714 2715 base::MessageLoop::current()->QuitWhenIdle(); 2716 } 2717 2718 bool policy_value_; 2719 bool request_url_allowed_via_whitelist_; 2720 GURL request_url_; 2721 static const char kExampleRequestPattern[]; 2722 }; 2723 2724 // static 2725 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] = 2726 "http://[*.]example.com/"; 2727 2728 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2729 AudioCaptureAllowed) { 2730 content::MediaStreamDevices audio_devices; 2731 content::MediaStreamDevice fake_audio_device( 2732 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device"); 2733 audio_devices.push_back(fake_audio_device); 2734 2735 PolicyMap policies; 2736 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL); 2737 UpdateProviderPolicy(policies); 2738 2739 content::BrowserThread::PostTaskAndReply( 2740 content::BrowserThread::IO, FROM_HERE, 2741 base::Bind(&MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged, 2742 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2743 audio_devices), 2744 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest, 2745 this)); 2746 2747 base::MessageLoop::current()->Run(); 2748 } 2749 2750 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2751 AudioCaptureAllowedUrls) { 2752 content::MediaStreamDevices audio_devices; 2753 content::MediaStreamDevice fake_audio_device( 2754 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device"); 2755 audio_devices.push_back(fake_audio_device); 2756 2757 const char* allow_pattern[] = { 2758 kExampleRequestPattern, 2759 // This will set an allow-all policy whitelist. Since we do not allow 2760 // setting an allow-all entry in the whitelist, this entry should be ignored 2761 // and therefore the request should be denied. 2762 NULL, 2763 }; 2764 2765 for (size_t i = 0; i < arraysize(allow_pattern); ++i) { 2766 PolicyMap policies; 2767 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, 2768 key::kAudioCaptureAllowedUrls, allow_pattern[i]); 2769 UpdateProviderPolicy(policies); 2770 2771 content::BrowserThread::PostTaskAndReply( 2772 content::BrowserThread::IO, FROM_HERE, 2773 base::Bind( 2774 &MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged, 2775 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2776 audio_devices), 2777 base::Bind( 2778 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest, 2779 this)); 2780 2781 base::MessageLoop::current()->Run(); 2782 } 2783 } 2784 2785 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2786 VideoCaptureAllowed) { 2787 content::MediaStreamDevices video_devices; 2788 content::MediaStreamDevice fake_video_device( 2789 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device"); 2790 video_devices.push_back(fake_video_device); 2791 2792 PolicyMap policies; 2793 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL); 2794 UpdateProviderPolicy(policies); 2795 2796 content::BrowserThread::PostTaskAndReply( 2797 content::BrowserThread::IO, FROM_HERE, 2798 base::Bind(&MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged, 2799 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2800 video_devices), 2801 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest, 2802 this)); 2803 2804 base::MessageLoop::current()->Run(); 2805 } 2806 2807 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2808 VideoCaptureAllowedUrls) { 2809 content::MediaStreamDevices video_devices; 2810 content::MediaStreamDevice fake_video_device( 2811 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device"); 2812 video_devices.push_back(fake_video_device); 2813 2814 const char* allow_pattern[] = { 2815 kExampleRequestPattern, 2816 // This will set an allow-all policy whitelist. Since we do not allow 2817 // setting an allow-all entry in the whitelist, this entry should be ignored 2818 // and therefore the request should be denied. 2819 NULL, 2820 }; 2821 2822 for (size_t i = 0; i < arraysize(allow_pattern); ++i) { 2823 PolicyMap policies; 2824 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, 2825 key::kVideoCaptureAllowedUrls, allow_pattern[i]); 2826 UpdateProviderPolicy(policies); 2827 2828 content::BrowserThread::PostTaskAndReply( 2829 content::BrowserThread::IO, FROM_HERE, 2830 base::Bind( 2831 &MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged, 2832 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2833 video_devices), 2834 base::Bind( 2835 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest, 2836 this)); 2837 2838 base::MessageLoop::current()->Run(); 2839 } 2840 } 2841 2842 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance, 2843 MediaStreamDevicesControllerBrowserTest, 2844 testing::Bool()); 2845 2846 #if !defined(OS_CHROMEOS) 2847 // Similar to PolicyTest but sets the proper policy before the browser is 2848 // started. 2849 class PolicyVariationsServiceTest : public PolicyTest { 2850 public: 2851 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 2852 PolicyTest::SetUpInProcessBrowserTestFixture(); 2853 PolicyMap policies; 2854 policies.Set( 2855 key::kVariationsRestrictParameter, 2856 POLICY_LEVEL_MANDATORY, 2857 POLICY_SCOPE_USER, 2858 base::Value::CreateStringValue("restricted"), 2859 NULL); 2860 provider_.UpdateChromePolicy(policies); 2861 } 2862 }; 2863 2864 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) { 2865 const std::string default_variations_url = 2866 chrome_variations::VariationsService:: 2867 GetDefaultVariationsServerURLForTesting(); 2868 2869 const GURL url = 2870 chrome_variations::VariationsService::GetVariationsServerURL( 2871 g_browser_process->local_state()); 2872 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true)); 2873 std::string value; 2874 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value)); 2875 EXPECT_EQ("restricted", value); 2876 } 2877 #endif 2878 2879 } // namespace policy 2880