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