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