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