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