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