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