policy_browsertest.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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/command_line.h" 12#include "base/file_util.h" 13#include "base/files/file_path.h" 14#include "base/files/scoped_temp_dir.h" 15#include "base/memory/ref_counted.h" 16#include "base/path_service.h" 17#include "base/prefs/pref_service.h" 18#include "base/run_loop.h" 19#include "base/string16.h" 20#include "base/string_util.h" 21#include "base/stringprintf.h" 22#include "base/test/test_file_util.h" 23#include "base/time.h" 24#include "base/utf_string_conversions.h" 25#include "base/values.h" 26#include "chrome/app/chrome_command_ids.h" 27#include "chrome/browser/autocomplete/autocomplete_controller.h" 28#include "chrome/browser/browser_process.h" 29#include "chrome/browser/content_settings/tab_specific_content_settings.h" 30#include "chrome/browser/devtools/devtools_window.h" 31#include "chrome/browser/download/download_prefs.h" 32#include "chrome/browser/extensions/crx_installer.h" 33#include "chrome/browser/extensions/extension_service.h" 34#include "chrome/browser/extensions/extension_system.h" 35#include "chrome/browser/infobars/infobar_service.h" 36#include "chrome/browser/media/media_capture_devices_dispatcher.h" 37#include "chrome/browser/media/media_stream_devices_controller.h" 38#include "chrome/browser/metrics/variations/variations_service.h" 39#include "chrome/browser/net/url_request_mock_util.h" 40#include "chrome/browser/plugins/plugin_prefs.h" 41#include "chrome/browser/policy/browser_policy_connector.h" 42#include "chrome/browser/policy/mock_configuration_policy_provider.h" 43#include "chrome/browser/policy/policy_map.h" 44#include "chrome/browser/prefs/session_startup_pref.h" 45#include "chrome/browser/profiles/profile.h" 46#include "chrome/browser/search/search.h" 47#include "chrome/browser/search_engines/template_url.h" 48#include "chrome/browser/search_engines/template_url_service.h" 49#include "chrome/browser/search_engines/template_url_service_factory.h" 50#include "chrome/browser/translate/translate_infobar_delegate.h" 51#include "chrome/browser/translate/translate_tab_helper.h" 52#include "chrome/browser/ui/bookmarks/bookmark_bar.h" 53#include "chrome/browser/ui/browser.h" 54#include "chrome/browser/ui/browser_commands.h" 55#include "chrome/browser/ui/browser_list.h" 56#include "chrome/browser/ui/browser_tabstrip.h" 57#include "chrome/browser/ui/browser_window.h" 58#include "chrome/browser/ui/host_desktop.h" 59#include "chrome/browser/ui/omnibox/location_bar.h" 60#include "chrome/browser/ui/omnibox/omnibox_edit_model.h" 61#include "chrome/browser/ui/omnibox/omnibox_view.h" 62#include "chrome/browser/ui/tabs/tab_strip_model.h" 63#include "chrome/common/chrome_notification_types.h" 64#include "chrome/common/chrome_paths.h" 65#include "chrome/common/chrome_process_type.h" 66#include "chrome/common/chrome_switches.h" 67#include "chrome/common/content_settings.h" 68#include "chrome/common/extensions/extension.h" 69#include "chrome/common/extensions/extension_constants.h" 70#include "chrome/common/pref_names.h" 71#include "chrome/common/url_constants.h" 72#include "chrome/test/base/in_process_browser_test.h" 73#include "chrome/test/base/ui_test_utils.h" 74#include "content/public/browser/browser_child_process_host_iterator.h" 75#include "content/public/browser/browser_context.h" 76#include "content/public/browser/browser_thread.h" 77#include "content/public/browser/child_process_data.h" 78#include "content/public/browser/download_item.h" 79#include "content/public/browser/download_manager.h" 80#include "content/public/browser/notification_registrar.h" 81#include "content/public/browser/notification_service.h" 82#include "content/public/browser/notification_source.h" 83#include "content/public/browser/notification_types.h" 84#include "content/public/browser/plugin_service.h" 85#include "content/public/browser/render_process_host.h" 86#include "content/public/browser/render_view_host.h" 87#include "content/public/browser/web_contents.h" 88#include "content/public/common/content_paths.h" 89#include "content/public/common/page_transition_types.h" 90#include "content/public/common/process_type.h" 91#include "content/public/common/url_constants.h" 92#include "content/public/test/browser_test_utils.h" 93#include "content/public/test/download_test_observer.h" 94#include "content/public/test/mock_notification_observer.h" 95#include "content/public/test/test_navigation_observer.h" 96#include "content/public/test/test_utils.h" 97#include "content/test/net/url_request_failed_job.h" 98#include "content/test/net/url_request_mock_http_job.h" 99#include "googleurl/src/gurl.h" 100#include "grit/generated_resources.h" 101#include "net/base/net_errors.h" 102#include "net/base/net_util.h" 103#include "net/base/url_util.h" 104#include "net/http/http_stream_factory.h" 105#include "net/url_request/url_request.h" 106#include "net/url_request/url_request_filter.h" 107#include "policy/policy_constants.h" 108#include "testing/gmock/include/gmock/gmock.h" 109#include "testing/gtest/include/gtest/gtest.h" 110#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" 111#include "ui/base/l10n/l10n_util.h" 112#include "ui/base/resource/resource_bundle.h" 113#include "webkit/plugins/npapi/plugin_utils.h" 114#include "webkit/plugins/plugin_constants.h" 115#include "webkit/plugins/webplugininfo.h" 116 117#if defined(OS_CHROMEOS) 118#include "ash/accelerators/accelerator_controller.h" 119#include "ash/accelerators/accelerator_table.h" 120#include "ash/shell.h" 121#include "ash/shell_delegate.h" 122#include "chrome/browser/chromeos/audio/audio_handler.h" 123#include "chromeos/audio/audio_pref_handler.h" 124#endif 125 126using content::BrowserThread; 127using content::URLRequestMockHTTPJob; 128using testing::AnyNumber; 129using testing::Mock; 130using testing::Return; 131using testing::_; 132 133namespace policy { 134 135namespace { 136 137const char kURL[] = "http://example.com"; 138const char kCookieValue[] = "converted=true"; 139// Assigned to Philip J. Fry to fix eventually. 140const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT"; 141 142const base::FilePath::CharType kTestExtensionsDir[] = 143 FILE_PATH_LITERAL("extensions"); 144const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx"); 145const base::FilePath::CharType kAdBlockCrxName[] = 146 FILE_PATH_LITERAL("adblock.crx"); 147const base::FilePath::CharType kHostedAppCrxName[] = 148 FILE_PATH_LITERAL("hosted_app.crx"); 149 150const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; 151const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn"; 152const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi"; 153 154const base::FilePath::CharType kGoodCrxManifestName[] = 155 FILE_PATH_LITERAL("good_update_manifest.xml"); 156 157// Filters requests to the hosts in |urls| and redirects them to the test data 158// dir through URLRequestMockHTTPJobs. 159void RedirectHostsToTestData(const char* const urls[], size_t size) { 160 // Map the given hosts to the test data dir. 161 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 162 base::FilePath base_path; 163 PathService::Get(chrome::DIR_TEST_DATA, &base_path); 164 for (size_t i = 0; i < size; ++i) { 165 const GURL url(urls[i]); 166 EXPECT_TRUE(url.is_valid()); 167 filter->AddUrlProtocolHandler(url, 168 URLRequestMockHTTPJob::CreateProtocolHandler(base_path)); 169 } 170} 171 172// Remove filters for requests to the hosts in |urls|. 173void UndoRedirectHostsToTestData(const char* const urls[], size_t size) { 174 // Map the given hosts to the test data dir. 175 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 176 for (size_t i = 0; i < size; ++i) { 177 const GURL url(urls[i]); 178 EXPECT_TRUE(url.is_valid()); 179 filter->RemoveUrlHandler(url); 180 } 181} 182 183// Fails requests using ERR_CONNECTION_RESET. 184net::URLRequestJob* FailedJobFactory( 185 net::URLRequest* request, 186 net::NetworkDelegate* network_delegate, 187 const std::string& scheme) { 188 return new content::URLRequestFailedJob( 189 request, network_delegate, net::ERR_CONNECTION_RESET); 190} 191 192// While |MakeRequestFail| is in scope URLRequests to |host| will fail. 193class MakeRequestFail { 194 public: 195 // Sets up the filter on IO thread such that requests to |host| fail. 196 explicit MakeRequestFail(const std::string& host) : host_(host) { 197 BrowserThread::PostTaskAndReply( 198 BrowserThread::IO, FROM_HERE, 199 base::Bind(MakeRequestFailOnIO, host_), 200 MessageLoop::QuitClosure()); 201 content::RunMessageLoop(); 202 } 203 ~MakeRequestFail() { 204 BrowserThread::PostTaskAndReply( 205 BrowserThread::IO, FROM_HERE, 206 base::Bind(UndoMakeRequestFailOnIO, host_), 207 MessageLoop::QuitClosure()); 208 content::RunMessageLoop(); 209 } 210 211 private: 212 // Filters requests to the |host| such that they fail. Run on IO thread. 213 static void MakeRequestFailOnIO(const std::string& host) { 214 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 215 filter->AddHostnameHandler("http", host, &FailedJobFactory); 216 filter->AddHostnameHandler("https", host, &FailedJobFactory); 217 } 218 219 // Remove filters for requests to the |host|. Run on IO thread. 220 static void UndoMakeRequestFailOnIO(const std::string& host) { 221 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 222 filter->RemoveHostnameHandler("http", host); 223 filter->RemoveHostnameHandler("https", host); 224 } 225 226 const std::string host_; 227}; 228 229// Verifies that the given url |spec| can be opened. This assumes that |spec| 230// points at empty.html in the test data dir. 231void CheckCanOpenURL(Browser* browser, const char* spec) { 232 GURL url(spec); 233 ui_test_utils::NavigateToURL(browser, url); 234 content::WebContents* contents = 235 browser->tab_strip_model()->GetActiveWebContents(); 236 EXPECT_EQ(url, contents->GetURL()); 237 EXPECT_EQ(net::FormatUrl(url, std::string()), contents->GetTitle()); 238} 239 240// Verifies that access to the given url |spec| is blocked. 241void CheckURLIsBlocked(Browser* browser, const char* spec) { 242 GURL url(spec); 243 ui_test_utils::NavigateToURL(browser, url); 244 content::WebContents* contents = 245 browser->tab_strip_model()->GetActiveWebContents(); 246 EXPECT_EQ(url, contents->GetURL()); 247 string16 title = UTF8ToUTF16(url.spec() + " was blocked"); 248 EXPECT_EQ(title, contents->GetTitle()); 249 250 // Verify that the expected error page is being displayed. 251 bool result = false; 252 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 253 contents, 254 "var textContent = document.body.textContent;" 255 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;" 256 "domAutomationController.send(hasError);", 257 &result)); 258 EXPECT_TRUE(result); 259} 260 261// Downloads a file named |file| and expects it to be saved to |dir|, which 262// must be empty. 263void DownloadAndVerifyFile( 264 Browser* browser, const base::FilePath& dir, const base::FilePath& file) { 265 content::DownloadManager* download_manager = 266 content::BrowserContext::GetDownloadManager(browser->profile()); 267 content::DownloadTestObserverTerminal observer( 268 download_manager, 1, 269 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); 270 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 271 base::FilePath downloaded = dir.Append(file); 272 EXPECT_FALSE(file_util::PathExists(downloaded)); 273 ui_test_utils::NavigateToURLWithDisposition( 274 browser, url, CURRENT_TAB, 275 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 276 observer.WaitForFinished(); 277 EXPECT_EQ( 278 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE)); 279 EXPECT_TRUE(file_util::PathExists(downloaded)); 280 file_util::FileEnumerator enumerator( 281 dir, false, file_util::FileEnumerator::FILES); 282 EXPECT_EQ(file, enumerator.Next().BaseName()); 283 EXPECT_EQ(base::FilePath(), enumerator.Next()); 284} 285 286#if defined(OS_CHROMEOS) 287int CountScreenshots() { 288 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext( 289 ash::Shell::GetInstance()->delegate()->GetCurrentBrowserContext()); 290 file_util::FileEnumerator enumerator(download_prefs->DownloadPath(), 291 false, file_util::FileEnumerator::FILES, 292 "Screenshot*"); 293 int count = 0; 294 while (!enumerator.Next().empty()) 295 count++; 296 return count; 297} 298#endif 299 300// Checks if WebGL is enabled in the given WebContents. 301bool IsWebGLEnabled(content::WebContents* contents) { 302 bool result = false; 303 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 304 contents, 305 "var canvas = document.createElement('canvas');" 306 "var context = canvas.getContext('experimental-webgl');" 307 "domAutomationController.send(context != null);", 308 &result)); 309 return result; 310} 311 312bool IsJavascriptEnabled(content::WebContents* contents) { 313 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue( 314 contents->GetRenderViewHost(), "123"); 315 int result = 0; 316 if (!value->GetAsInteger(&result)) 317 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType()); 318 return result == 123; 319} 320 321void CopyPluginListAndQuit(std::vector<webkit::WebPluginInfo>* out, 322 const std::vector<webkit::WebPluginInfo>& in) { 323 *out = in; 324 MessageLoop::current()->QuitWhenIdle(); 325} 326 327template<typename T> 328void CopyValueAndQuit(T* out, T in) { 329 *out = in; 330 MessageLoop::current()->QuitWhenIdle(); 331} 332 333void GetPluginList(std::vector<webkit::WebPluginInfo>* plugins) { 334 content::PluginService* service = content::PluginService::GetInstance(); 335 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins)); 336 content::RunMessageLoop(); 337} 338 339const webkit::WebPluginInfo* GetFlashPlugin( 340 const std::vector<webkit::WebPluginInfo>& plugins) { 341 const webkit::WebPluginInfo* flash = NULL; 342 for (size_t i = 0; i < plugins.size(); ++i) { 343 if (plugins[i].name == ASCIIToUTF16(kFlashPluginName)) { 344 flash = &plugins[i]; 345 break; 346 } 347 } 348#if defined(OFFICIAL_BUILD) 349 // Official builds bundle Flash. 350 EXPECT_TRUE(flash); 351#else 352 if (!flash) 353 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found."; 354#endif 355 return flash; 356} 357 358bool SetPluginEnabled(PluginPrefs* plugin_prefs, 359 const webkit::WebPluginInfo* plugin, 360 bool enabled) { 361 bool ok = false; 362 plugin_prefs->EnablePlugin(enabled, plugin->path, 363 base::Bind(CopyValueAndQuit<bool>, &ok)); 364 content::RunMessageLoop(); 365 return ok; 366} 367 368int CountPluginsOnIOThread() { 369 int count = 0; 370 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) { 371 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN || 372 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) { 373 count++; 374 } 375 } 376 return count; 377} 378 379int CountPlugins() { 380 int count = -1; 381 BrowserThread::PostTaskAndReplyWithResult( 382 BrowserThread::IO, FROM_HERE, 383 base::Bind(CountPluginsOnIOThread), 384 base::Bind(CopyValueAndQuit<int>, &count)); 385 content::RunMessageLoop(); 386 EXPECT_GE(count, 0); 387 return count; 388} 389 390void FlushBlacklistPolicy() { 391 // Updates of the URLBlacklist are done on IO, after building the blacklist 392 // on FILE, which is initiated from IO. 393 content::RunAllPendingInMessageLoop(BrowserThread::IO); 394 content::RunAllPendingInMessageLoop(BrowserThread::FILE); 395 content::RunAllPendingInMessageLoop(BrowserThread::IO); 396} 397 398bool ContainsVisibleElement(content::WebContents* contents, 399 const std::string& id) { 400 bool result; 401 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 402 contents, 403 "var elem = document.getElementById('" + id + "');" 404 "domAutomationController.send(!!elem && !elem.hidden);", 405 &result)); 406 return result; 407} 408 409#if defined(OS_CHROMEOS) 410// Volume observer mock used by the audio policy tests. 411class TestVolumeObserver : public chromeos::AudioHandler::VolumeObserver { 412 public: 413 TestVolumeObserver() {} 414 virtual ~TestVolumeObserver() {} 415 416 MOCK_METHOD0(OnVolumeChanged, void()); 417 MOCK_METHOD0(OnMuteToggled, void()); 418 419 private: 420 DISALLOW_COPY_AND_ASSIGN(TestVolumeObserver); 421}; 422#endif 423 424} // namespace 425 426class PolicyTest : public InProcessBrowserTest { 427 protected: 428 PolicyTest() {} 429 virtual ~PolicyTest() {} 430 431 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 432 EXPECT_CALL(provider_, IsInitializationComplete(_)) 433 .WillRepeatedly(Return(true)); 434 EXPECT_CALL(provider_, RegisterPolicyDomain(_, _)).Times(AnyNumber()); 435 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); 436 } 437 438 virtual void SetUpOnMainThread() OVERRIDE { 439 BrowserThread::PostTask( 440 BrowserThread::IO, FROM_HERE, 441 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true)); 442 } 443 444 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA 445 // instead of chrome::DIR_TEST_DATA. 446 void ServeContentTestData() { 447 base::FilePath root_http; 448 PathService::Get(content::DIR_TEST_DATA, &root_http); 449 BrowserThread::PostTaskAndReply( 450 BrowserThread::IO, FROM_HERE, 451 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http), 452 MessageLoop::current()->QuitWhenIdleClosure()); 453 content::RunMessageLoop(); 454 } 455 456 void SetScreenshotPolicy(bool enabled) { 457 PolicyMap policies; 458 policies.Set(key::kDisableScreenshots, POLICY_LEVEL_MANDATORY, 459 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(!enabled)); 460 UpdateProviderPolicy(policies); 461 } 462 463 void TestScreenshotFeedback(bool enabled) { 464 SetScreenshotPolicy(enabled); 465 466 // Wait for feedback page to load. 467 content::WindowedNotificationObserver observer( 468 content::NOTIFICATION_LOAD_STOP, 469 content::NotificationService::AllSources()); 470 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_FEEDBACK)); 471 observer.Wait(); 472 content::WebContents* web_contents = 473 static_cast<content::Source<content::NavigationController> >( 474 observer.source())->GetWebContents(); 475 476 // Wait for feedback page to fully initialize. 477 // setupCurrentScreenshot is called when feedback page loads and (among 478 // other things) adds current-screenshots-thumbnailDiv-0-image element. 479 // The code below executes either before setupCurrentScreenshot was called 480 // (setupCurrentScreenshot is replaced with our hook) or after it has 481 // completed (in that case send result immediately). 482 bool result = false; 483 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 484 web_contents, 485 "function btest_initCompleted(url) {" 486 " var img = new Image();" 487 " img.src = url;" 488 " img.onload = function() {" 489 " domAutomationController.send(img.width * img.height > 0);" 490 " };" 491 " img.onerror = function() {" 492 " domAutomationController.send(false);" 493 " };" 494 "}" 495 "function setupCurrentScreenshot(url) {" 496 " btest_initCompleted(url);" 497 "}" 498 "var img = document.getElementById(" 499 " 'current-screenshots-thumbnailDiv-0-image');" 500 "if (img)" 501 " btest_initCompleted(img.src);", 502 &result)); 503 EXPECT_EQ(enabled, result); 504 505 // Feedback page is a singleton page, so close so future calls to this 506 // function work as expected. 507 web_contents->Close(); 508 } 509 510#if defined(OS_CHROMEOS) 511 void TestScreenshotFile(bool enabled) { 512 SetScreenshotPolicy(enabled); 513 ash::Shell::GetInstance()->accelerator_controller()->PerformAction( 514 ash::TAKE_SCREENSHOT, ui::Accelerator()); 515 516 // TAKE_SCREENSHOT handler posts write file task on success, wait for it. 517 BrowserThread::PostTaskAndReply( 518 BrowserThread::IO, 519 FROM_HERE, 520 base::Bind(base::DoNothing), 521 MessageLoop::QuitClosure()); 522 content::RunMessageLoop(); 523 } 524#endif 525 526 ExtensionService* extension_service() { 527 extensions::ExtensionSystem* system = 528 extensions::ExtensionSystem::Get(browser()->profile()); 529 return system->extension_service(); 530 } 531 532 const extensions::Extension* InstallExtension( 533 const base::FilePath::StringType& name) { 534 base::FilePath extension_path(ui_test_utils::GetTestFilePath( 535 base::FilePath(kTestExtensionsDir), base::FilePath(name))); 536 scoped_refptr<extensions::CrxInstaller> installer = 537 extensions::CrxInstaller::Create(extension_service(), NULL); 538 installer->set_allow_silent_install(true); 539 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE); 540 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE); 541 542 content::WindowedNotificationObserver observer( 543 chrome::NOTIFICATION_CRX_INSTALLER_DONE, 544 content::NotificationService::AllSources()); 545 installer->InstallCrx(extension_path); 546 observer.Wait(); 547 content::Details<const extensions::Extension> details = observer.details(); 548 return details.ptr(); 549 } 550 551 void UninstallExtension(const std::string& id, bool expect_success) { 552 content::WindowedNotificationObserver observer( 553 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED 554 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED, 555 content::NotificationService::AllSources()); 556 extension_service()->UninstallExtension(id, false, NULL); 557 observer.Wait(); 558 } 559 560 void UpdateProviderPolicy(const PolicyMap& policy) { 561 provider_.UpdateChromePolicy(policy); 562 DCHECK(MessageLoop::current()); 563 base::RunLoop loop; 564 loop.RunUntilIdle(); 565 } 566 567 // Sends a mouse click at the given coordinates to the current renderer. 568 void PerformClick(int x, int y) { 569 content::WebContents* contents = 570 browser()->tab_strip_model()->GetActiveWebContents(); 571 WebKit::WebMouseEvent click_event; 572 click_event.type = WebKit::WebInputEvent::MouseDown; 573 click_event.button = WebKit::WebMouseEvent::ButtonLeft; 574 click_event.clickCount = 1; 575 click_event.x = x; 576 click_event.y = y; 577 contents->GetRenderViewHost()->ForwardMouseEvent(click_event); 578 click_event.type = WebKit::WebInputEvent::MouseUp; 579 contents->GetRenderViewHost()->ForwardMouseEvent(click_event); 580 } 581 582 MockConfigurationPolicyProvider provider_; 583}; 584 585#if defined(OS_WIN) 586// This policy only exists on Windows. 587 588// Sets the locale policy before the browser is started. 589class LocalePolicyTest : public PolicyTest { 590 public: 591 LocalePolicyTest() {} 592 virtual ~LocalePolicyTest() {} 593 594 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 595 PolicyTest::SetUpInProcessBrowserTestFixture(); 596 PolicyMap policies; 597 policies.Set( 598 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 599 base::Value::CreateStringValue("fr")); 600 provider_.UpdateChromePolicy(policies); 601 // The "en-US" ResourceBundle is always loaded before this step for tests, 602 // but in this test we want the browser to load the bundle as it 603 // normally would. 604 ResourceBundle::CleanupSharedInstance(); 605 } 606}; 607 608IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) { 609 // Verifies that the default locale can be overridden with policy. 610 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); 611 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 612 string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); 613 string16 title; 614 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title)); 615 EXPECT_EQ(french_title, title); 616 617 // Make sure this is really French and differs from the English title. 618 std::string loaded = 619 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US"); 620 EXPECT_EQ("en-US", loaded); 621 string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); 622 EXPECT_NE(french_title, english_title); 623} 624#endif 625 626IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) { 627 // Verifies that the bookmarks bar can be forced to always or never show up. 628 629 // Test starts in about:blank. 630 PrefService* prefs = browser()->profile()->GetPrefs(); 631 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 632 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 633 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state()); 634 635 PolicyMap policies; 636 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, 637 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 638 UpdateProviderPolicy(policies); 639 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 640 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 641 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state()); 642 643 // The NTP has special handling of the bookmark bar. 644 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 645 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state()); 646 647 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, 648 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 649 UpdateProviderPolicy(policies); 650 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 651 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 652 // The bookmark bar is hidden in the NTP when disabled by policy. 653 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state()); 654 655 policies.Clear(); 656 UpdateProviderPolicy(policies); 657 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar)); 658 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar)); 659 // The bookmark bar is shown detached in the NTP, when disabled by prefs only. 660 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state()); 661} 662 663IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_ClearSiteDataOnExit) { 664 // Verifies that cookies are deleted on shutdown. This test is split in 3 665 // parts because it spans 2 browser restarts. 666 667 Profile* profile = browser()->profile(); 668 GURL url(kURL); 669 // No cookies at startup. 670 EXPECT_TRUE(content::GetCookies(profile, url).empty()); 671 // Set a cookie now. 672 std::string value = std::string(kCookieValue) + std::string(kCookieOptions); 673 EXPECT_TRUE(content::SetCookie(profile, url, value)); 674 // Verify it was set. 675 EXPECT_EQ(kCookieValue, GetCookies(profile, url)); 676} 677 678IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_ClearSiteDataOnExit) { 679 // Verify that the cookie persists across restarts. 680 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL))); 681 // Now set the policy and the cookie should be gone after another restart. 682 PolicyMap policies; 683 policies.Set(key::kClearSiteDataOnExit, POLICY_LEVEL_MANDATORY, 684 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 685 UpdateProviderPolicy(policies); 686} 687 688IN_PROC_BROWSER_TEST_F(PolicyTest, ClearSiteDataOnExit) { 689 // Verify that the cookie is gone. 690 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty()); 691} 692 693IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) { 694 MakeRequestFail make_request_fail("search.example"); 695 696 // Verifies that a default search is made using the provider configured via 697 // policy. Also checks that default search can be completely disabled. 698 const string16 kKeyword(ASCIIToUTF16("testsearch")); 699 const std::string kSearchURL("http://search.example/search?q={searchTerms}"); 700 const std::string kAlternateURL0( 701 "http://search.example/search#q={searchTerms}"); 702 const std::string kAlternateURL1("http://search.example/#q={searchTerms}"); 703 const std::string kSearchTermsReplacementKey("zekey"); 704 705 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 706 browser()->profile()); 707 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 708 TemplateURL* default_search = service->GetDefaultSearchProvider(); 709 ASSERT_TRUE(default_search); 710 EXPECT_NE(kKeyword, default_search->keyword()); 711 EXPECT_NE(kSearchURL, default_search->url()); 712 EXPECT_FALSE( 713 default_search->alternate_urls().size() == 2 && 714 default_search->alternate_urls()[0] == kAlternateURL0 && 715 default_search->alternate_urls()[1] == kAlternateURL1 && 716 default_search->search_terms_replacement_key() == 717 kSearchTermsReplacementKey); 718 719 // Override the default search provider using policies. 720 PolicyMap policies; 721 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 722 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 723 policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY, 724 POLICY_SCOPE_USER, base::Value::CreateStringValue(kKeyword)); 725 policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY, 726 POLICY_SCOPE_USER, base::Value::CreateStringValue(kSearchURL)); 727 base::ListValue* alternate_urls = new base::ListValue(); 728 alternate_urls->AppendString(kAlternateURL0); 729 alternate_urls->AppendString(kAlternateURL1); 730 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY, 731 POLICY_SCOPE_USER, alternate_urls); 732 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey, 733 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 734 base::Value::CreateStringValue(kSearchTermsReplacementKey)); 735 UpdateProviderPolicy(policies); 736 default_search = service->GetDefaultSearchProvider(); 737 ASSERT_TRUE(default_search); 738 EXPECT_EQ(kKeyword, default_search->keyword()); 739 EXPECT_EQ(kSearchURL, default_search->url()); 740 EXPECT_EQ(2U, default_search->alternate_urls().size()); 741 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]); 742 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]); 743 EXPECT_EQ(kSearchTermsReplacementKey, 744 default_search->search_terms_replacement_key()); 745 746 // Verify that searching from the omnibox uses kSearchURL. 747 chrome::FocusLocationBar(browser()); 748 LocationBar* location_bar = browser()->window()->GetLocationBar(); 749 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for"); 750 OmniboxEditModel* model = location_bar->GetLocationEntry()->model(); 751 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 752 content::WebContents* web_contents = 753 browser()->tab_strip_model()->GetActiveWebContents(); 754 GURL expected("http://search.example/search?q=stuff+to+search+for"); 755 EXPECT_EQ(expected, web_contents->GetURL()); 756 757 // Verify that searching from the omnibox can be disabled. 758 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); 759 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 760 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 761 EXPECT_TRUE(service->GetDefaultSearchProvider()); 762 UpdateProviderPolicy(policies); 763 EXPECT_FALSE(service->GetDefaultSearchProvider()); 764 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work"); 765 // This means that submitting won't trigger any action. 766 EXPECT_FALSE(model->CurrentMatch().destination_url.is_valid()); 767 EXPECT_EQ(GURL(chrome::kAboutBlankURL), web_contents->GetURL()); 768} 769 770IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) { 771 // Makes the requests fail since all we want to check is that the redirection 772 // is done properly. 773 MakeRequestFail make_request_fail("google.com"); 774 775 // Verifies that requests to Google Search engine with the SafeSearch 776 // enabled set the safe=active&ssui=on parameters at the end of the query. 777 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 778 browser()->profile()); 779 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 780 781 // First check that nothing happens. 782 content::TestNavigationObserver no_safesearch_observer( 783 content::NotificationService::AllSources()); 784 chrome::FocusLocationBar(browser()); 785 LocationBar* location_bar = browser()->window()->GetLocationBar(); 786 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/"); 787 OmniboxEditModel* model = location_bar->GetLocationEntry()->model(); 788 no_safesearch_observer.Wait(); 789 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 790 content::WebContents* web_contents = 791 browser()->tab_strip_model()->GetActiveWebContents(); 792 GURL expected_without("http://google.com/"); 793 EXPECT_EQ(expected_without, web_contents->GetURL()); 794 795 PrefService* prefs = browser()->profile()->GetPrefs(); 796 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch)); 797 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch)); 798 799 // Override the default SafeSearch setting using policies. 800 PolicyMap policies; 801 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY, 802 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 803 UpdateProviderPolicy(policies); 804 805 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch)); 806 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch)); 807 808 content::TestNavigationObserver safesearch_observer( 809 content::NotificationService::AllSources()); 810 811 // Verify that searching from google.com works. 812 chrome::FocusLocationBar(browser()); 813 location_bar = browser()->window()->GetLocationBar(); 814 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/"); 815 safesearch_observer.Wait(); 816 model = location_bar->GetLocationEntry()->model(); 817 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 818 web_contents = browser()->tab_strip_model()->GetActiveWebContents(); 819 std::string expected_url("http://google.com/?"); 820 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" + 821 chrome::kSafeSearchSsuiParameter; 822 GURL expected_with_parameters(expected_url); 823 EXPECT_EQ(expected_with_parameters, web_contents->GetURL()); 824} 825 826IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) { 827 MakeRequestFail make_request_fail("search.example"); 828 829 chrome::EnableInstantExtendedAPIForTesting(); 830 browser()->toolbar_model()->SetSupportsExtractionOfURLLikeSearchTerms(true); 831 832 // Verifies that a default search is made using the provider configured via 833 // policy. Also checks that default search can be completely disabled. 834 const string16 kKeyword(ASCIIToUTF16("testsearch")); 835 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}"); 836 const std::string kInstantURL("http://does/not/exist"); 837 const std::string kAlternateURL0( 838 "https://www.google.com/search#q={searchTerms}"); 839 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}"); 840 const std::string kSearchTermsReplacementKey( 841 "{google:instantExtendedEnabledKey}"); 842 843 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( 844 browser()->profile()); 845 ui_test_utils::WaitForTemplateURLServiceToLoad(service); 846 TemplateURL* default_search = service->GetDefaultSearchProvider(); 847 ASSERT_TRUE(default_search); 848 EXPECT_NE(kKeyword, default_search->keyword()); 849 EXPECT_NE(kSearchURL, default_search->url()); 850 EXPECT_NE(kInstantURL, default_search->instant_url()); 851 EXPECT_FALSE( 852 default_search->alternate_urls().size() == 2 && 853 default_search->alternate_urls()[0] == kAlternateURL0 && 854 default_search->alternate_urls()[1] == kAlternateURL1); 855 856 // Override the default search provider using policies. 857 PolicyMap policies; 858 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY, 859 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 860 policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY, 861 POLICY_SCOPE_USER, base::Value::CreateStringValue(kKeyword)); 862 policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY, 863 POLICY_SCOPE_USER, base::Value::CreateStringValue(kSearchURL)); 864 policies.Set(key::kDefaultSearchProviderInstantURL, POLICY_LEVEL_MANDATORY, 865 POLICY_SCOPE_USER, base::Value::CreateStringValue(kInstantURL)); 866 base::ListValue* alternate_urls = new base::ListValue(); 867 alternate_urls->AppendString(kAlternateURL0); 868 alternate_urls->AppendString(kAlternateURL1); 869 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY, 870 POLICY_SCOPE_USER, alternate_urls); 871 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey, 872 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 873 base::Value::CreateStringValue(kSearchTermsReplacementKey)); 874 UpdateProviderPolicy(policies); 875 default_search = service->GetDefaultSearchProvider(); 876 ASSERT_TRUE(default_search); 877 EXPECT_EQ(kKeyword, default_search->keyword()); 878 EXPECT_EQ(kSearchURL, default_search->url()); 879 EXPECT_EQ(kInstantURL, default_search->instant_url()); 880 EXPECT_EQ(2U, default_search->alternate_urls().size()); 881 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]); 882 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]); 883 884 // Verify that searching from the omnibox does search term replacement with 885 // first URL pattern. 886 chrome::FocusLocationBar(browser()); 887 LocationBar* location_bar = browser()->window()->GetLocationBar(); 888 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 889 "https://www.google.com/?espv=1#q=foobar"); 890 OmniboxEditModel* model = location_bar->GetLocationEntry()->model(); 891 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 892 EXPECT_EQ(ASCIIToUTF16("foobar"), model->CurrentMatch().contents); 893 894 // Verify that not using espv=1 does not do search term replacement. 895 chrome::FocusLocationBar(browser()); 896 location_bar = browser()->window()->GetLocationBar(); 897 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 898 "https://www.google.com/?q=foobar"); 899 model = location_bar->GetLocationEntry()->model(); 900 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 901 EXPECT_EQ(ASCIIToUTF16("https://www.google.com/?q=foobar"), 902 model->CurrentMatch().contents); 903 904 // Verify that searching from the omnibox does search term replacement with 905 // second URL pattern. 906 chrome::FocusLocationBar(browser()); 907 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 908 "https://www.google.com/search?espv=1#q=banana"); 909 model = location_bar->GetLocationEntry()->model(); 910 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 911 EXPECT_EQ(ASCIIToUTF16("banana"), model->CurrentMatch().contents); 912 913 // Verify that searching from the omnibox does search term replacement with 914 // standard search URL pattern. 915 chrome::FocusLocationBar(browser()); 916 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 917 "https://www.google.com/search?q=tractor+parts&espv=1"); 918 model = location_bar->GetLocationEntry()->model(); 919 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 920 EXPECT_EQ(ASCIIToUTF16("tractor parts"), model->CurrentMatch().contents); 921 922 // Verify that searching from the omnibox prioritizes hash over query. 923 chrome::FocusLocationBar(browser()); 924 ui_test_utils::SendToOmniboxAndSubmit(location_bar, 925 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar"); 926 model = location_bar->GetLocationEntry()->model(); 927 EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid()); 928 EXPECT_EQ(ASCIIToUTF16("foobar"), model->CurrentMatch().contents); 929} 930 931// The linux and win bots can't create a GL context. http://crbug.com/103379 932#if defined(OS_MACOSX) 933IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) { 934 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); 935 // WebGL is enabled by default. 936 content::WebContents* contents = 937 browser()->tab_strip_model()->GetActiveWebContents(); 938 EXPECT_TRUE(IsWebGLEnabled(contents)); 939 // Disable with a policy. 940 PolicyMap policies; 941 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, 942 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 943 UpdateProviderPolicy(policies); 944 // Crash and reload the tab to get a new renderer. 945 content::CrashTab(contents); 946 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD)); 947 EXPECT_FALSE(IsWebGLEnabled(contents)); 948 // Enable with a policy. 949 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, 950 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 951 UpdateProviderPolicy(policies); 952 content::CrashTab(contents); 953 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD)); 954 EXPECT_TRUE(IsWebGLEnabled(contents)); 955} 956#endif 957 958IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) { 959 // Verifies that SPDY can be disable by policy. 960 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled()); 961 PolicyMap policies; 962 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY, 963 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 964 UpdateProviderPolicy(policies); 965 content::RunAllPendingInMessageLoop(); 966 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled()); 967 // Verify that it can be force-enabled too. 968 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true); 969 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY, 970 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 971 UpdateProviderPolicy(policies); 972 content::RunAllPendingInMessageLoop(); 973 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled()); 974} 975 976IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) { 977 // Verifies that plugins can be forced to be disabled by policy. 978 979 // Verify that the Flash plugin exists and that it can be enabled and disabled 980 // by the user. 981 std::vector<webkit::WebPluginInfo> plugins; 982 GetPluginList(&plugins); 983 const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins); 984 if (!flash) 985 return; 986 PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile()); 987 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 988 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 989 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 990 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true)); 991 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 992 993 // Now disable it with a policy. 994 base::ListValue disabled_plugins; 995 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*")); 996 PolicyMap policies; 997 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 998 POLICY_SCOPE_USER, disabled_plugins.DeepCopy()); 999 UpdateProviderPolicy(policies); 1000 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1001 // The user shouldn't be able to enable it. 1002 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true)); 1003 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1004} 1005 1006IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) { 1007 // Verifies that plugins with an exception in the blacklist can be enabled. 1008 1009 // Verify that the Flash plugin exists and that it can be enabled and disabled 1010 // by the user. 1011 std::vector<webkit::WebPluginInfo> plugins; 1012 GetPluginList(&plugins); 1013 const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins); 1014 if (!flash) 1015 return; 1016 PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile()); 1017 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1018 1019 // Disable all plugins. 1020 base::ListValue disabled_plugins; 1021 disabled_plugins.Append(base::Value::CreateStringValue("*")); 1022 PolicyMap policies; 1023 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 1024 POLICY_SCOPE_USER, disabled_plugins.DeepCopy()); 1025 UpdateProviderPolicy(policies); 1026 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1027 // The user shouldn't be able to enable it. 1028 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true)); 1029 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1030 1031 // Now open an exception for flash. 1032 base::ListValue disabled_plugins_exceptions; 1033 disabled_plugins_exceptions.Append( 1034 base::Value::CreateStringValue("*Flash*")); 1035 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY, 1036 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy()); 1037 UpdateProviderPolicy(policies); 1038 // It should revert to the user's preference automatically. 1039 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1040 // And the user should be able to disable and enable again. 1041 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 1042 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1043 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true)); 1044 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1045} 1046 1047IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) { 1048 // Verifies that a plugin can be force-installed with a policy. 1049 std::vector<webkit::WebPluginInfo> plugins; 1050 GetPluginList(&plugins); 1051 const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins); 1052 if (!flash) 1053 return; 1054 PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile()); 1055 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1056 1057 // The user disables it and then a policy forces it to be enabled. 1058 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false)); 1059 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash)); 1060 base::ListValue plugin_list; 1061 plugin_list.Append(base::Value::CreateStringValue(kFlashPluginName)); 1062 PolicyMap policies; 1063 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY, 1064 POLICY_SCOPE_USER, plugin_list.DeepCopy()); 1065 UpdateProviderPolicy(policies); 1066 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1067 // The user can't disable it anymore. 1068 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false)); 1069 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1070 1071 // When a plugin is both enabled and disabled, the whitelist takes precedence. 1072 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY, 1073 POLICY_SCOPE_USER, plugin_list.DeepCopy()); 1074 UpdateProviderPolicy(policies); 1075 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash)); 1076} 1077 1078IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) { 1079 // Verifies that dangerous plugins can be always authorized to run with 1080 // a policy. 1081 1082 // Verify that the test page exists. It is only present in checkouts with 1083 // src-internal. 1084 if (!file_util::PathExists(ui_test_utils::GetTestFilePath( 1085 base::FilePath(FILE_PATH_LITERAL("plugin")), 1086 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) { 1087 LOG(INFO) << 1088 "Test skipped because plugin/quicktime.html test file wasn't found."; 1089 return; 1090 } 1091 1092 ServeContentTestData(); 1093 // No plugins at startup. 1094 EXPECT_EQ(0, CountPlugins()); 1095 1096 content::WebContents* contents = 1097 browser()->tab_strip_model()->GetActiveWebContents(); 1098 ASSERT_TRUE(contents); 1099 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents); 1100 ASSERT_TRUE(infobar_service); 1101 EXPECT_EQ(0u, infobar_service->infobar_count()); 1102 1103 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html")); 1104 GURL url(URLRequestMockHTTPJob::GetMockUrl(path)); 1105 ui_test_utils::NavigateToURL(browser(), url); 1106 // This should have triggered the dangerous plugin infobar. 1107 ASSERT_EQ(1u, infobar_service->infobar_count()); 1108 InfoBarDelegate* infobar_delegate = infobar_service->infobar_at(0); 1109 EXPECT_TRUE(infobar_delegate->AsConfirmInfoBarDelegate()); 1110 // And the plugin isn't running. 1111 EXPECT_EQ(0, CountPlugins()); 1112 1113 // Now set a policy to always authorize this. 1114 PolicyMap policies; 1115 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY, 1116 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1117 UpdateProviderPolicy(policies); 1118 // Reloading the page shouldn't trigger the infobar this time. 1119 ui_test_utils::NavigateToURL(browser(), url); 1120 EXPECT_EQ(0u, infobar_service->infobar_count()); 1121 // And the plugin started automatically. 1122 EXPECT_EQ(1, CountPlugins()); 1123} 1124 1125IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) { 1126 // Verifies that access to the developer tools can be disabled. 1127 1128 // Open devtools. 1129 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS)); 1130 content::WebContents* contents = 1131 browser()->tab_strip_model()->GetActiveWebContents(); 1132 EXPECT_TRUE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents)); 1133 1134 // Disable devtools via policy. 1135 PolicyMap policies; 1136 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY, 1137 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1138 UpdateProviderPolicy(policies); 1139 // The existing devtools window should have closed. 1140 EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents)); 1141 // And it's not possible to open it again. 1142 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS)); 1143 EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents)); 1144} 1145 1146IN_PROC_BROWSER_TEST_F(PolicyTest, WebStoreIconHidden) { 1147 // Verifies that the web store icons can be hidden from the new tab page. 1148 1149 // Open new tab page and look for the web store icons. 1150 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 1151 content::WebContents* contents = 1152 browser()->tab_strip_model()->GetActiveWebContents(); 1153 1154#if !defined(OS_CHROMEOS) 1155 // Look for web store's app ID in the apps page. 1156 EXPECT_TRUE(ContainsVisibleElement(contents, 1157 "ahfgeienlihckogmohjhadlkjgocpleb")); 1158#endif 1159 1160 // The next NTP has no footer. 1161 if (ContainsVisibleElement(contents, "footer")) 1162 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link")); 1163 1164 // Turn off the web store icons. 1165 PolicyMap policies; 1166 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY, 1167 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1168 UpdateProviderPolicy(policies); 1169 1170 // The web store icons should now be hidden. 1171 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); 1172 EXPECT_FALSE(ContainsVisibleElement(contents, 1173 "ahfgeienlihckogmohjhadlkjgocpleb")); 1174 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link")); 1175} 1176 1177// This policy isn't available on Chrome OS. 1178#if !defined(OS_CHROMEOS) 1179IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) { 1180 // Verifies that the download directory can be forced by policy. 1181 1182 // Set the initial download directory. 1183 base::ScopedTempDir initial_dir; 1184 ASSERT_TRUE(initial_dir.CreateUniqueTempDir()); 1185 browser()->profile()->GetPrefs()->SetFilePath( 1186 prefs::kDownloadDefaultDirectory, initial_dir.path()); 1187 // Don't prompt for the download location during this test. 1188 browser()->profile()->GetPrefs()->SetBoolean( 1189 prefs::kPromptForDownload, false); 1190 1191 // Verify that downloads end up on the default directory. 1192 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1193 DownloadAndVerifyFile(browser(), initial_dir.path(), file); 1194 file_util::DieFileDie(initial_dir.path().Append(file), false); 1195 1196 // Override the download directory with the policy and verify a download. 1197 base::ScopedTempDir forced_dir; 1198 ASSERT_TRUE(forced_dir.CreateUniqueTempDir()); 1199 PolicyMap policies; 1200 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY, 1201 POLICY_SCOPE_USER, 1202 base::Value::CreateStringValue(forced_dir.path().value())); 1203 UpdateProviderPolicy(policies); 1204 DownloadAndVerifyFile(browser(), forced_dir.path(), file); 1205 // Verify that the first download location wasn't affected. 1206 EXPECT_FALSE(file_util::PathExists(initial_dir.path().Append(file))); 1207} 1208#endif 1209 1210IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklist) { 1211 // Verifies that blacklisted extensions can't be installed. 1212 ExtensionService* service = extension_service(); 1213 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1214 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1215 base::ListValue blacklist; 1216 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId)); 1217 PolicyMap policies; 1218 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1219 POLICY_SCOPE_USER, blacklist.DeepCopy()); 1220 UpdateProviderPolicy(policies); 1221 1222 // "good.crx" is blacklisted. 1223 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1224 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1225 1226 // "adblock.crx" is not. 1227 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName); 1228 ASSERT_TRUE(adblock); 1229 EXPECT_EQ(kAdBlockCrxId, adblock->id()); 1230 EXPECT_EQ(adblock, 1231 service->GetExtensionById(kAdBlockCrxId, true)); 1232 1233 // Now blacklist all extensions. 1234 blacklist.Clear(); 1235 blacklist.Append(base::Value::CreateStringValue("*")); 1236 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1237 POLICY_SCOPE_USER, blacklist.DeepCopy()); 1238 UpdateProviderPolicy(policies); 1239 // AdBlock was automatically removed. 1240 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1241 // And can't be installed again, nor can good.crx. 1242 EXPECT_FALSE(InstallExtension(kAdBlockCrxName)); 1243 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1244 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1245 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1246} 1247 1248IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) { 1249 // Verifies that the whitelist can open exceptions to the blacklist. 1250 ExtensionService* service = extension_service(); 1251 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1252 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1253 base::ListValue blacklist; 1254 blacklist.Append(base::Value::CreateStringValue("*")); 1255 base::ListValue whitelist; 1256 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId)); 1257 PolicyMap policies; 1258 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY, 1259 POLICY_SCOPE_USER, blacklist.DeepCopy()); 1260 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY, 1261 POLICY_SCOPE_USER, whitelist.DeepCopy()); 1262 UpdateProviderPolicy(policies); 1263 // "adblock.crx" is blacklisted. 1264 EXPECT_FALSE(InstallExtension(kAdBlockCrxName)); 1265 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true)); 1266 // "good.crx" has a whitelist exception. 1267 const extensions::Extension* good = InstallExtension(kGoodCrxName); 1268 ASSERT_TRUE(good); 1269 EXPECT_EQ(kGoodCrxId, good->id()); 1270 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true)); 1271 // The user can also remove this extension. 1272 UninstallExtension(kGoodCrxId, true); 1273} 1274 1275IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) { 1276 // Verifies that extensions that are force-installed by policies are 1277 // installed and can't be uninstalled. 1278 ExtensionService* service = extension_service(); 1279 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1280 1281 // Extensions that are force-installed come from an update URL, which defaults 1282 // to the webstore. Use a mock URL for this test with an update manifest 1283 // that includes "good.crx". 1284 base::FilePath path = 1285 base::FilePath(kTestExtensionsDir).Append(kGoodCrxManifestName); 1286 GURL url(URLRequestMockHTTPJob::GetMockUrl(path)); 1287 1288 // Setting the forcelist extension should install "good.crx". 1289 base::ListValue forcelist; 1290 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf( 1291 "%s;%s", kGoodCrxId, url.spec().c_str()))); 1292 PolicyMap policies; 1293 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY, 1294 POLICY_SCOPE_USER, forcelist.DeepCopy()); 1295 content::WindowedNotificationObserver observer( 1296 chrome::NOTIFICATION_EXTENSION_INSTALLED, 1297 content::NotificationService::AllSources()); 1298 UpdateProviderPolicy(policies); 1299 observer.Wait(); 1300 // Note: Cannot check that the notification details match the expected 1301 // exception, since the details object has already been freed prior to 1302 // the completion of observer.Wait(). 1303 1304 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true)); 1305 1306 // The user is not allowed to uninstall force-installed extensions. 1307 UninstallExtension(kGoodCrxId, false); 1308} 1309 1310IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) { 1311 // Verifies that extensions are blocked if policy specifies an allowed types 1312 // list and the extension's type is not on that list. 1313 ExtensionService* service = extension_service(); 1314 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1315 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true)); 1316 1317 base::ListValue allowed_types; 1318 allowed_types.AppendString("hosted_app"); 1319 PolicyMap policies; 1320 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY, 1321 POLICY_SCOPE_USER, allowed_types.DeepCopy()); 1322 UpdateProviderPolicy(policies); 1323 1324 // "good.crx" is blocked. 1325 EXPECT_FALSE(InstallExtension(kGoodCrxName)); 1326 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true)); 1327 1328 // "hosted_app.crx" is of a whitelisted type. 1329 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName); 1330 ASSERT_TRUE(hosted_app); 1331 EXPECT_EQ(kHostedAppCrxId, hosted_app->id()); 1332 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true)); 1333 1334 // The user can remove the extension. 1335 UninstallExtension(kHostedAppCrxId, true); 1336} 1337 1338// Checks that a click on an extension CRX download triggers the extension 1339// installation prompt without further user interaction when the source is 1340// whitelisted by policy. 1341IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallSources) { 1342 CommandLine::ForCurrentProcess()->AppendSwitchASCII( 1343 switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); 1344 1345 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl( 1346 base::FilePath(FILE_PATH_LITERAL("extensions/*")))); 1347 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl( 1348 base::FilePath(FILE_PATH_LITERAL("policy/*")))); 1349 1350 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath( 1351 FILE_PATH_LITERAL("policy/extension_install_sources_test.html")))); 1352 ui_test_utils::NavigateToURL(browser(), download_page_url); 1353 1354 // As long as the policy is not present, extensions are considered dangerous. 1355 content::DownloadTestObserverTerminal download_observer( 1356 content::BrowserContext::GetDownloadManager(browser()->profile()), 1, 1357 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY); 1358 PerformClick(0, 0); 1359 download_observer.WaitForFinished(); 1360 1361 // Install the policy and trigger another download. 1362 base::ListValue install_sources; 1363 install_sources.AppendString(install_source_url.spec()); 1364 install_sources.AppendString(referrer_url.spec()); 1365 PolicyMap policies; 1366 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY, 1367 POLICY_SCOPE_USER, install_sources.DeepCopy()); 1368 UpdateProviderPolicy(policies); 1369 1370 content::WindowedNotificationObserver observer( 1371 chrome::NOTIFICATION_EXTENSION_INSTALLED, 1372 content::NotificationService::AllSources()); 1373 PerformClick(1, 0); 1374 observer.Wait(); 1375 // Note: Cannot check that the notification details match the expected 1376 // exception, since the details object has already been freed prior to 1377 // the completion of observer.Wait(). 1378 1379 // The first extension shouldn't be present, the second should be there. 1380 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true)); 1381 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false)); 1382} 1383 1384IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) { 1385 // Verifies that the homepage can be configured with policies. 1386 // Set a default, and check that the home button navigates there. 1387 browser()->profile()->GetPrefs()->SetString( 1388 prefs::kHomePage, chrome::kChromeUIPolicyURL); 1389 browser()->profile()->GetPrefs()->SetBoolean( 1390 prefs::kHomePageIsNewTabPage, false); 1391 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), 1392 browser()->profile()->GetHomePage()); 1393 content::WebContents* contents = 1394 browser()->tab_strip_model()->GetActiveWebContents(); 1395 EXPECT_EQ(GURL(chrome::kAboutBlankURL), contents->GetURL()); 1396 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1397 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL()); 1398 1399 // Now override with policy. 1400 PolicyMap policies; 1401 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY, 1402 POLICY_SCOPE_USER, 1403 base::Value::CreateStringValue(chrome::kChromeUICreditsURL)); 1404 UpdateProviderPolicy(policies); 1405 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1406 content::WaitForLoadStop(contents); 1407 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL()); 1408 1409 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, 1410 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1411 UpdateProviderPolicy(policies); 1412 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME)); 1413 content::WaitForLoadStop(contents); 1414 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL()); 1415} 1416 1417IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) { 1418 // Verifies that incognito windows can't be opened when disabled by policy. 1419 1420 // Only test this on the native desktop. 1421 const BrowserList* native_browser_list = 1422 BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE); 1423 1424 // Disable incognito via policy and verify that incognito windows can't be 1425 // opened. 1426 EXPECT_EQ(1u, native_browser_list->size()); 1427 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive()); 1428 PolicyMap policies; 1429 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY, 1430 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 1431 UpdateProviderPolicy(policies); 1432 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW)); 1433 EXPECT_EQ(1u, native_browser_list->size()); 1434 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive()); 1435 1436 // Enable via policy and verify that incognito windows can be opened. 1437 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY, 1438 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1439 UpdateProviderPolicy(policies); 1440 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW)); 1441 EXPECT_EQ(2u, native_browser_list->size()); 1442 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive()); 1443} 1444 1445IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) { 1446 // Verifies that Javascript can be disabled. 1447 content::WebContents* contents = 1448 browser()->tab_strip_model()->GetActiveWebContents(); 1449 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1450 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS)); 1451 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE)); 1452 1453 // Disable Javascript via policy. 1454 PolicyMap policies; 1455 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY, 1456 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 1457 UpdateProviderPolicy(policies); 1458 // Reload the page. 1459 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); 1460 EXPECT_FALSE(IsJavascriptEnabled(contents)); 1461 // Developer tools still work when javascript is disabled. 1462 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS)); 1463 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE)); 1464 // Javascript is always enabled for the internal pages. 1465 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL)); 1466 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1467 1468 // The javascript content setting policy overrides the javascript policy. 1469 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); 1470 EXPECT_FALSE(IsJavascriptEnabled(contents)); 1471 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY, 1472 POLICY_SCOPE_USER, 1473 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW)); 1474 UpdateProviderPolicy(policies); 1475 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); 1476 EXPECT_TRUE(IsJavascriptEnabled(contents)); 1477} 1478 1479IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) { 1480 // Verifies that browsing history is not saved. 1481 PolicyMap policies; 1482 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY, 1483 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1484 UpdateProviderPolicy(policies); 1485 GURL url = ui_test_utils::GetTestUrl( 1486 base::FilePath(base::FilePath::kCurrentDirectory), 1487 base::FilePath(FILE_PATH_LITERAL("empty.html"))); 1488 ui_test_utils::NavigateToURL(browser(), url); 1489 // Verify that the navigation wasn't saved in the history. 1490 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile()); 1491 EXPECT_EQ(0u, enumerator1.urls().size()); 1492 1493 // Now flip the policy and try again. 1494 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY, 1495 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 1496 UpdateProviderPolicy(policies); 1497 ui_test_utils::NavigateToURL(browser(), url); 1498 // Verify that the navigation was saved in the history. 1499 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile()); 1500 ASSERT_EQ(1u, enumerator2.urls().size()); 1501 EXPECT_EQ(url, enumerator2.urls()[0]); 1502} 1503 1504IN_PROC_BROWSER_TEST_F(PolicyTest, TranslateEnabled) { 1505 // Verifies that translate can be forced enabled or disabled by policy. 1506 1507 // Get the InfoBarService, and verify that there are no infobars on startup. 1508 content::WebContents* contents = 1509 browser()->tab_strip_model()->GetActiveWebContents(); 1510 ASSERT_TRUE(contents); 1511 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents); 1512 ASSERT_TRUE(infobar_service); 1513 EXPECT_EQ(0u, infobar_service->infobar_count()); 1514 1515 // Force enable the translate feature. 1516 PolicyMap policies; 1517 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY, 1518 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1519 UpdateProviderPolicy(policies); 1520 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test 1521 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the 1522 // TranslateManager observes. This allows checking that an infobar is NOT 1523 // shown below, without polling for infobars for some indeterminate amount 1524 // of time. 1525 GURL url = ui_test_utils::GetTestUrl( 1526 base::FilePath(), 1527 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html"))); 1528 content::WindowedNotificationObserver language_observer1( 1529 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, 1530 content::NotificationService::AllSources()); 1531 ui_test_utils::NavigateToURL(browser(), url); 1532 language_observer1.Wait(); 1533 1534 // Verify the translation detected for this tab. 1535 TranslateTabHelper* translate_tab_helper = 1536 TranslateTabHelper::FromWebContents(contents); 1537 ASSERT_TRUE(translate_tab_helper); 1538 LanguageState& language_state = translate_tab_helper->language_state(); 1539 EXPECT_EQ("fr", language_state.original_language()); 1540 EXPECT_TRUE(language_state.page_translatable()); 1541 EXPECT_FALSE(language_state.translation_pending()); 1542 EXPECT_FALSE(language_state.translation_declined()); 1543 EXPECT_FALSE(language_state.IsPageTranslated()); 1544 1545 // Verify that the translate infobar showed up. 1546 ASSERT_EQ(1u, infobar_service->infobar_count()); 1547 InfoBarDelegate* infobar_delegate = infobar_service->infobar_at(0); 1548 TranslateInfoBarDelegate* delegate = 1549 infobar_delegate->AsTranslateInfoBarDelegate(); 1550 ASSERT_TRUE(delegate); 1551 EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE, 1552 delegate->infobar_type()); 1553 EXPECT_EQ("fr", delegate->original_language_code()); 1554 1555 // Now force disable translate. 1556 infobar_service->RemoveInfoBar(infobar_delegate); 1557 EXPECT_EQ(0u, infobar_service->infobar_count()); 1558 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY, 1559 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 1560 UpdateProviderPolicy(policies); 1561 // Navigating to the same URL now doesn't trigger an infobar. 1562 content::WindowedNotificationObserver language_observer2( 1563 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, 1564 content::NotificationService::AllSources()); 1565 ui_test_utils::NavigateToURL(browser(), url); 1566 language_observer2.Wait(); 1567 EXPECT_EQ(0u, infobar_service->infobar_count()); 1568} 1569 1570IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) { 1571 // Checks that URLs can be blacklisted, and that exceptions can be made to 1572 // the blacklist. 1573 1574 // Filter |kURLS| on IO thread, so that requests to those hosts end up 1575 // as URLRequestMockHTTPJobs. 1576 const char* kURLS[] = { 1577 "http://aaa.com/empty.html", 1578 "http://bbb.com/empty.html", 1579 "http://sub.bbb.com/empty.html", 1580 "http://bbb.com/policy/blank.html", 1581 }; 1582 { 1583 base::RunLoop loop; 1584 BrowserThread::PostTaskAndReply( 1585 BrowserThread::IO, FROM_HERE, 1586 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)), 1587 loop.QuitClosure()); 1588 loop.Run(); 1589 } 1590 1591 // Verify that "bbb.com" opens before applying the blacklist. 1592 CheckCanOpenURL(browser(), kURLS[1]); 1593 1594 // Set a blacklist. 1595 base::ListValue blacklist; 1596 blacklist.Append(base::Value::CreateStringValue("bbb.com")); 1597 PolicyMap policies; 1598 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, 1599 POLICY_SCOPE_USER, blacklist.DeepCopy()); 1600 UpdateProviderPolicy(policies); 1601 FlushBlacklistPolicy(); 1602 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked. 1603 CheckCanOpenURL(browser(), kURLS[0]); 1604 for (size_t i = 1; i < arraysize(kURLS); ++i) 1605 CheckURLIsBlocked(browser(), kURLS[i]); 1606 1607 // Whitelist some sites of bbb.com. 1608 base::ListValue whitelist; 1609 whitelist.Append(base::Value::CreateStringValue("sub.bbb.com")); 1610 whitelist.Append(base::Value::CreateStringValue("bbb.com/policy")); 1611 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, 1612 POLICY_SCOPE_USER, whitelist.DeepCopy()); 1613 UpdateProviderPolicy(policies); 1614 FlushBlacklistPolicy(); 1615 CheckURLIsBlocked(browser(), kURLS[1]); 1616 CheckCanOpenURL(browser(), kURLS[2]); 1617 CheckCanOpenURL(browser(), kURLS[3]); 1618 1619 { 1620 base::RunLoop loop; 1621 BrowserThread::PostTaskAndReply( 1622 BrowserThread::IO, FROM_HERE, 1623 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)), 1624 loop.QuitClosure()); 1625 loop.Run(); 1626 } 1627} 1628 1629// Flaky on Linux. http://crbug.com/155459 1630#if defined(OS_LINUX) 1631#define MAYBE_DisableScreenshotsFeedback DISABLED_DisableScreenshotsFeedback 1632#else 1633#define MAYBE_DisableScreenshotsFeedback DisableScreenshotsFeedback 1634#endif 1635IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_DisableScreenshotsFeedback) { 1636 // Make sure current screenshot can be taken and displayed on feedback page. 1637 TestScreenshotFeedback(true); 1638 1639 // Check if banning screenshots disabled feedback page's ability to grab a 1640 // screenshot. 1641 TestScreenshotFeedback(false); 1642} 1643 1644#if defined(OS_CHROMEOS) 1645IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) { 1646 int screenshot_count = CountScreenshots(); 1647 1648 // Make sure screenshots are counted correctly. 1649 TestScreenshotFile(true); 1650 ASSERT_EQ(CountScreenshots(), screenshot_count + 1); 1651 1652 // Check if trying to take a screenshot fails when disabled by policy. 1653 TestScreenshotFile(false); 1654 ASSERT_EQ(CountScreenshots(), screenshot_count + 1); 1655} 1656 1657// TODO(rkc,jennyz): Fix this once we remove the old Audio Handler completely. 1658IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_DisableAudioOutput) { 1659 // Set up the mock observer. 1660 chromeos::AudioHandler::Initialize( 1661 chromeos::AudioPrefHandler::Create(g_browser_process->local_state())); 1662 chromeos::AudioHandler* audio_handler = chromeos::AudioHandler::GetInstance(); 1663 scoped_ptr<TestVolumeObserver> mock(new TestVolumeObserver()); 1664 audio_handler->AddVolumeObserver(mock.get()); 1665 1666 bool prior_state = audio_handler->IsMuted(); 1667 // Make sure we are not muted and then toggle the policy and observe if the 1668 // trigger was successful. 1669 audio_handler->SetMuted(false); 1670 EXPECT_FALSE(audio_handler->IsMuted()); 1671 EXPECT_CALL(*mock, OnMuteToggled()).Times(1); 1672 PolicyMap policies; 1673 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY, 1674 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false)); 1675 UpdateProviderPolicy(policies); 1676 EXPECT_TRUE(audio_handler->IsMuted()); 1677 // This should not change the state now and should not trigger OnMuteToggled. 1678 audio_handler->SetMuted(false); 1679 EXPECT_TRUE(audio_handler->IsMuted()); 1680 1681 // Toggle back and observe if the trigger was successful. 1682 EXPECT_CALL(*mock, OnMuteToggled()).Times(1); 1683 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY, 1684 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true)); 1685 UpdateProviderPolicy(policies); 1686 EXPECT_FALSE(audio_handler->IsMuted()); 1687 EXPECT_CALL(*mock, OnMuteToggled()).Times(1); 1688 audio_handler->SetMuted(true); 1689 EXPECT_TRUE(audio_handler->IsMuted()); 1690 // Revert the prior state. 1691 EXPECT_CALL(*mock, OnMuteToggled()).Times(1); 1692 audio_handler->SetMuted(prior_state); 1693 audio_handler->RemoveVolumeObserver(mock.get()); 1694 chromeos::AudioHandler::Shutdown(); 1695} 1696 1697IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_SessionLengthLimit) { 1698 // Set the session start time to 2 hours ago. 1699 g_browser_process->local_state()->SetInt64( 1700 prefs::kSessionStartTime, 1701 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2)) 1702 .ToInternalValue()); 1703} 1704 1705IN_PROC_BROWSER_TEST_F(PolicyTest, SessionLengthLimit) { 1706 content::MockNotificationObserver observer; 1707 content::NotificationRegistrar registrar; 1708 registrar.Add(&observer, 1709 chrome::NOTIFICATION_APP_TERMINATING, 1710 content::NotificationService::AllSources()); 1711 1712 // Set the session length limit to 3 hours. Verify that the session is not 1713 // terminated. 1714 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)) 1715 .Times(0); 1716 PolicyMap policies; 1717 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 1718 POLICY_SCOPE_USER, 1719 base::Value::CreateIntegerValue(180 * 60 * 1000)); // 3 hours. 1720 UpdateProviderPolicy(policies); 1721 base::RunLoop().RunUntilIdle(); 1722 Mock::VerifyAndClearExpectations(&observer); 1723 1724 // Decrease the session length limit to 1 hour. Verify that the session is 1725 // terminated immediately. 1726 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _)); 1727 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY, 1728 POLICY_SCOPE_USER, 1729 base::Value::CreateIntegerValue(60 * 60 * 1000)); // 1 hour. 1730 UpdateProviderPolicy(policies); 1731 base::RunLoop().RunUntilIdle(); 1732 Mock::VerifyAndClearExpectations(&observer); 1733} 1734#endif 1735 1736namespace { 1737 1738static const char* kRestoredURLs[] = { 1739 "http://aaa.com/empty.html", 1740 "http://bbb.com/empty.html", 1741}; 1742 1743bool IsNonSwitchArgument(const CommandLine::StringType& s) { 1744 return s.empty() || s[0] != '-'; 1745} 1746 1747} // namespace 1748 1749// Similar to PolicyTest but allows setting policies before the browser is 1750// created. Each test parameter is a method that sets up the early policies 1751// and stores the expected startup URLs in |expected_urls_|. 1752class RestoreOnStartupPolicyTest 1753 : public PolicyTest, 1754 public testing::WithParamInterface< 1755 void (RestoreOnStartupPolicyTest::*)(void)> { 1756 public: 1757 RestoreOnStartupPolicyTest() {} 1758 virtual ~RestoreOnStartupPolicyTest() {} 1759 1760#if defined(OS_CHROMEOS) 1761 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { 1762 // TODO(nkostylev): Investigate if we can remove this switch. 1763 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests); 1764 PolicyTest::SetUpCommandLine(command_line); 1765 } 1766#endif 1767 1768 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 1769 PolicyTest::SetUpInProcessBrowserTestFixture(); 1770 // Set early policies now, before the browser is created. 1771 (this->*(GetParam()))(); 1772 1773 // Remove the non-switch arguments, so that session restore kicks in for 1774 // these tests. 1775 CommandLine* command_line = CommandLine::ForCurrentProcess(); 1776 CommandLine::StringVector argv = command_line->argv(); 1777 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument), 1778 argv.end()); 1779 command_line->InitFromArgv(argv); 1780 ASSERT_TRUE(std::equal(argv.begin(), argv.end(), 1781 command_line->argv().begin())); 1782 1783 // Redirect the test URLs to the test data directory. 1784 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs)); 1785 } 1786 1787 void HomepageIsNotNTP() { 1788 // Verifies that policy can set the startup pages to the homepage, when 1789 // the homepage is not the NTP. 1790 PolicyMap policies; 1791 policies.Set( 1792 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1793 base::Value::CreateIntegerValue( 1794 SessionStartupPref::kPrefValueHomePage)); 1795 policies.Set( 1796 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1797 base::Value::CreateBooleanValue(false)); 1798 policies.Set( 1799 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1800 base::Value::CreateStringValue(kRestoredURLs[1])); 1801 provider_.UpdateChromePolicy(policies); 1802 1803 expected_urls_.push_back(GURL(kRestoredURLs[1])); 1804 } 1805 1806 void HomepageIsNTP() { 1807 // Verifies that policy can set the startup pages to the homepage, when 1808 // the homepage is the NTP. 1809 PolicyMap policies; 1810 policies.Set( 1811 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1812 base::Value::CreateIntegerValue( 1813 SessionStartupPref::kPrefValueHomePage)); 1814 policies.Set( 1815 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1816 base::Value::CreateBooleanValue(true)); 1817 provider_.UpdateChromePolicy(policies); 1818 1819 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL)); 1820 } 1821 1822 void ListOfURLs() { 1823 // Verifies that policy can set the startup pages to a list of URLs. 1824 base::ListValue urls; 1825 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) { 1826 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i])); 1827 expected_urls_.push_back(GURL(kRestoredURLs[i])); 1828 } 1829 PolicyMap policies; 1830 policies.Set( 1831 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1832 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs)); 1833 policies.Set( 1834 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1835 urls.DeepCopy()); 1836 provider_.UpdateChromePolicy(policies); 1837 } 1838 1839 void NTP() { 1840 // Verifies that policy can set the startup page to the NTP. 1841 PolicyMap policies; 1842 policies.Set( 1843 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1844 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab)); 1845 provider_.UpdateChromePolicy(policies); 1846 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL)); 1847 } 1848 1849 void Last() { 1850 // Verifies that policy can set the startup pages to the last session. 1851 PolicyMap policies; 1852 policies.Set( 1853 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1854 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast)); 1855 provider_.UpdateChromePolicy(policies); 1856 // This should restore the tabs opened at PRE_RunTest below. 1857 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) 1858 expected_urls_.push_back(GURL(kRestoredURLs[i])); 1859 } 1860 1861 std::vector<GURL> expected_urls_; 1862}; 1863 1864IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) { 1865 // Open some tabs to verify if they are restored after the browser restarts. 1866 // Most policy settings override this, except kPrefValueLast which enforces 1867 // a restore. 1868 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0])); 1869 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) { 1870 content::WindowedNotificationObserver observer( 1871 content::NOTIFICATION_LOAD_STOP, 1872 content::NotificationService::AllSources()); 1873 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]), 1874 content::PAGE_TRANSITION_LINK); 1875 observer.Wait(); 1876 } 1877} 1878 1879IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) { 1880 TabStripModel* model = browser()->tab_strip_model(); 1881 int size = static_cast<int>(expected_urls_.size()); 1882 EXPECT_EQ(size, model->count()); 1883 for (int i = 0; i < size && i < model->count(); ++i) { 1884 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL()); 1885 } 1886} 1887 1888INSTANTIATE_TEST_CASE_P( 1889 RestoreOnStartupPolicyTestInstance, 1890 RestoreOnStartupPolicyTest, 1891 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP, 1892 &RestoreOnStartupPolicyTest::HomepageIsNTP, 1893 &RestoreOnStartupPolicyTest::ListOfURLs, 1894 &RestoreOnStartupPolicyTest::NTP, 1895 &RestoreOnStartupPolicyTest::Last)); 1896 1897// Similar to PolicyTest but sets a couple of policies before the browser is 1898// started. 1899class PolicyStatisticsCollectorTest : public PolicyTest { 1900 public: 1901 PolicyStatisticsCollectorTest() {} 1902 virtual ~PolicyStatisticsCollectorTest() {} 1903 1904 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 1905 PolicyTest::SetUpInProcessBrowserTestFixture(); 1906 PolicyMap policies; 1907 policies.Set( 1908 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1909 base::Value::CreateBooleanValue(true)); 1910 policies.Set( 1911 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1912 base::Value::CreateBooleanValue(false)); 1913 policies.Set( 1914 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 1915 base::Value::CreateStringValue("http://chromium.org")); 1916 provider_.UpdateChromePolicy(policies); 1917 } 1918}; 1919 1920IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) { 1921 // Verifies that policy usage histograms are collected at startup. 1922 1923 // BrowserPolicyConnector::Init() has already been called. Make sure the 1924 // CompleteInitialization() task has executed as well. 1925 content::RunAllPendingInMessageLoop(); 1926 1927 GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) + 1928 std::string(content::kStandardSchemeSeparator) + 1929 std::string(content::kChromeUIHistogramHost)); 1930 ui_test_utils::NavigateToURL(browser(), kAboutHistograms); 1931 content::WebContents* contents = 1932 browser()->tab_strip_model()->GetActiveWebContents(); 1933 std::string text; 1934 ASSERT_TRUE(content::ExecuteScriptAndExtractString( 1935 contents, 1936 "var nodes = document.querySelectorAll('body > pre');" 1937 "var result = '';" 1938 "for (var i = 0; i < nodes.length; ++i) {" 1939 " var text = nodes[i].innerHTML;" 1940 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {" 1941 " result = text;" 1942 " break;" 1943 " }" 1944 "}" 1945 "domAutomationController.send(result);", 1946 &text)); 1947 ASSERT_FALSE(text.empty()); 1948 const std::string kExpectedLabel = 1949 "Histogram: Enterprise.Policies recorded 3 samples"; 1950 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size())); 1951 // HomepageLocation has policy ID 1. 1952 EXPECT_NE(std::string::npos, text.find("<br>1 ---")); 1953 // ShowHomeButton has policy ID 35. 1954 EXPECT_NE(std::string::npos, text.find("<br>35 ---")); 1955 // BookmarkBarEnabled has policy ID 82. 1956 EXPECT_NE(std::string::npos, text.find("<br>82 ---")); 1957} 1958 1959class MediaStreamDevicesControllerBrowserTest 1960 : public PolicyTest, 1961 public testing::WithParamInterface<bool> { 1962 public: 1963 MediaStreamDevicesControllerBrowserTest() { 1964 policy_value_ = GetParam(); 1965 } 1966 virtual ~MediaStreamDevicesControllerBrowserTest() {} 1967 1968 void Accept(const content::MediaStreamDevices& devices, 1969 scoped_ptr<content::MediaStreamUI> ui) { 1970 if (policy_value_) { 1971 ASSERT_EQ(1U, devices.size()); 1972 ASSERT_EQ("fake_dev", devices[0].id); 1973 } else { 1974 ASSERT_EQ(0U, devices.size()); 1975 } 1976 } 1977 1978 void FinishAudioTest() { 1979 content::MediaStreamRequest request(0, 0, GURL(), 1980 content::MEDIA_OPEN_DEVICE, "fake_dev", 1981 content::MEDIA_DEVICE_AUDIO_CAPTURE, 1982 content::MEDIA_NO_SERVICE); 1983 MediaStreamDevicesController controller( 1984 browser()->tab_strip_model()->GetActiveWebContents(), request, 1985 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this)); 1986 controller.DismissInfoBarAndTakeActionOnSettings(); 1987 1988 MessageLoop::current()->QuitWhenIdle(); 1989 } 1990 1991 void FinishVideoTest() { 1992 content::MediaStreamRequest request(0, 0, GURL(), 1993 content::MEDIA_OPEN_DEVICE, "fake_dev", 1994 content::MEDIA_NO_SERVICE, 1995 content::MEDIA_DEVICE_VIDEO_CAPTURE); 1996 MediaStreamDevicesController controller( 1997 browser()->tab_strip_model()->GetActiveWebContents(), request, 1998 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this)); 1999 controller.DismissInfoBarAndTakeActionOnSettings(); 2000 2001 MessageLoop::current()->QuitWhenIdle(); 2002 } 2003 2004 bool policy_value_; 2005}; 2006 2007IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2008 AudioCaptureAllowed) { 2009 content::MediaStreamDevices audio_devices; 2010 content::MediaStreamDevice fake_audio_device( 2011 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device"); 2012 audio_devices.push_back(fake_audio_device); 2013 2014 PolicyMap policies; 2015 policies.Set(key::kAudioCaptureAllowed, POLICY_LEVEL_MANDATORY, 2016 POLICY_SCOPE_USER, 2017 base::Value::CreateBooleanValue(policy_value_)); 2018 UpdateProviderPolicy(policies); 2019 2020 content::BrowserThread::PostTaskAndReply( 2021 content::BrowserThread::IO, FROM_HERE, 2022 base::Bind(&MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged, 2023 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2024 audio_devices), 2025 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest, 2026 this)); 2027 2028 MessageLoop::current()->Run(); 2029} 2030 2031IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest, 2032 VideoCaptureAllowed) { 2033 content::MediaStreamDevices video_devices; 2034 content::MediaStreamDevice fake_video_device( 2035 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device"); 2036 video_devices.push_back(fake_video_device); 2037 2038 PolicyMap policies; 2039 policies.Set(key::kVideoCaptureAllowed, POLICY_LEVEL_MANDATORY, 2040 POLICY_SCOPE_USER, 2041 base::Value::CreateBooleanValue(policy_value_)); 2042 UpdateProviderPolicy(policies); 2043 2044 content::BrowserThread::PostTaskAndReply( 2045 content::BrowserThread::IO, FROM_HERE, 2046 base::Bind(&MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged, 2047 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()), 2048 video_devices), 2049 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest, 2050 this)); 2051 2052 MessageLoop::current()->Run(); 2053} 2054 2055INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance, 2056 MediaStreamDevicesControllerBrowserTest, 2057 testing::Bool()); 2058 2059#if !defined(OS_CHROMEOS) 2060// Similar to PolicyTest but sets the proper policy before the browser is 2061// started. 2062class PolicyVariationsServiceTest : public PolicyTest { 2063 public: 2064 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 2065 PolicyTest::SetUpInProcessBrowserTestFixture(); 2066 PolicyMap policies; 2067 policies.Set( 2068 key::kVariationsRestrictParameter, 2069 POLICY_LEVEL_MANDATORY, 2070 POLICY_SCOPE_USER, 2071 base::Value::CreateStringValue("restricted")); 2072 provider_.UpdateChromePolicy(policies); 2073 } 2074}; 2075 2076IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) { 2077 const std::string default_variations_url = 2078 chrome_variations::VariationsService:: 2079 GetDefaultVariationsServerURLForTesting(); 2080 2081 const GURL url = 2082 chrome_variations::VariationsService::GetVariationsServerURL( 2083 g_browser_process->local_state()); 2084 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true)); 2085 std::string value; 2086 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value)); 2087 EXPECT_EQ("restricted", value); 2088} 2089#endif 2090 2091} // namespace policy 2092