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 #ifndef CHROME_TEST_BASE_TESTING_PROFILE_H_ 6 #define CHROME_TEST_BASE_TESTING_PROFILE_H_ 7 8 #include <map> 9 #include <memory> 10 #include <string> 11 #include <utility> 12 #include <vector> 13 14 #include "base/macros.h" 15 #include "base/memory/ref_counted.h" 16 #include "base/optional.h" 17 #include "base/test/scoped_feature_list.h" 18 #include "build/build_config.h" 19 #include "chrome/browser/profiles/profile.h" 20 #include "chrome/common/buildflags.h" 21 #include "components/domain_reliability/clear_mode.h" 22 #include "components/keyed_service/content/browser_context_keyed_service_factory.h" 23 #include "components/keyed_service/core/simple_factory_key.h" 24 #include "content/public/browser/browser_thread.h" 25 #include "extensions/buildflags/buildflags.h" 26 #include "mojo/public/cpp/bindings/receiver_set.h" 27 #include "net/cookies/cookie_store.h" 28 #include "services/network/public/mojom/network_context.mojom.h" 29 #include "services/network/public/mojom/network_service.mojom.h" 30 #include "services/service_manager/public/mojom/service.mojom.h" 31 32 #if defined(OS_CHROMEOS) 33 #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" 34 #endif 35 36 class BrowserContextDependencyManager; 37 class SimpleDependencyManager; 38 class ExtensionSpecialStoragePolicy; 39 class HostContentSettingsMap; 40 class TestingPrefStore; 41 42 namespace content { 43 class MockResourceContext; 44 class SSLHostStateDelegate; 45 #if !defined(OS_ANDROID) 46 class ZoomLevelDelegate; 47 #endif // !defined(OS_ANDROID) 48 } // namespace content 49 50 namespace net { 51 class CookieStore; 52 } 53 54 namespace policy { 55 class PolicyService; 56 class ProfilePolicyConnector; 57 class SchemaRegistryService; 58 #if defined(OS_CHROMEOS) 59 class UserCloudPolicyManagerChromeOS; 60 #else 61 class UserCloudPolicyManager; 62 #endif // defined(OS_CHROMEOS) 63 } // namespace policy 64 65 namespace storage { 66 class SpecialStoragePolicy; 67 } 68 69 namespace sync_preferences { 70 class PrefServiceSyncable; 71 class TestingPrefServiceSyncable; 72 } // namespace sync_preferences 73 74 class TestingProfile : public Profile { 75 public: 76 // Profile directory name for the test user. This is "Default" on most 77 // platforms but must be different on ChromeOS because a logged-in user cannot 78 // use "Default" as profile directory. 79 // Browser- and UI tests should always use this to get to the user's profile 80 // directory. Unit-tests, though, should use |kInitialProfile|, which is 81 // always "Default", because they are runnining without logged-in user. 82 static const char kTestUserProfileDir[]; 83 84 // Sets the feature list to enable/disable ephemeral Guest profiles. 85 // Returns true if ephemeral Guest profiles are supported on the platform and 86 // feature list is initialized. 87 // TODO(https://crbug.com/1125474): Expand to cover ChromeOS when ChromeOS 88 // code supports ephemeral Guest profiles. 89 static bool SetScopedFeatureListForEphemeralGuestProfiles( 90 base::test::ScopedFeatureList& scoped_feature_list, 91 bool enabled); 92 93 // Default constructor that cannot be used with multi-profiles. 94 TestingProfile(); 95 96 using TestingFactories = 97 std::vector<std::pair<BrowserContextKeyedServiceFactory*, 98 BrowserContextKeyedServiceFactory::TestingFactory>>; 99 100 // Helper class for building an instance of TestingProfile (allows injecting 101 // mocks for various services prior to profile initialization). 102 // TODO(atwilson): Remove non-default constructors and various setters in 103 // favor of using the Builder API. 104 class Builder { 105 public: 106 Builder(); 107 Builder(const Builder&) = delete; 108 Builder& operator=(const Builder&) = delete; 109 ~Builder(); 110 111 // Sets a Delegate to be called back during profile init. This causes the 112 // final initialization to be performed via a task so the caller must run 113 // a MessageLoop. Caller maintains ownership of the Delegate 114 // and must manage its lifetime so it continues to exist until profile 115 // initialization is complete. 116 void SetDelegate(Delegate* delegate); 117 118 // Adds a testing factory to the TestingProfile. These testing factories 119 // are applied before the ProfileKeyedServices are created. 120 void AddTestingFactory( 121 BrowserContextKeyedServiceFactory* service_factory, 122 BrowserContextKeyedServiceFactory::TestingFactory testing_factory); 123 124 // Add multiple testing factories to the TestingProfile. These testing 125 // factories are applied before the ProfileKeyedServices are created. 126 void AddTestingFactories(const TestingFactories& testing_factories); 127 128 #if BUILDFLAG(ENABLE_EXTENSIONS) 129 // Sets the ExtensionSpecialStoragePolicy to be returned by 130 // GetExtensionSpecialStoragePolicy(). 131 void SetExtensionSpecialStoragePolicy( 132 scoped_refptr<ExtensionSpecialStoragePolicy> policy); 133 #endif 134 135 // Sets the path to the directory to be used to hold profile data. 136 void SetPath(const base::FilePath& path); 137 138 // Sets the PrefService to be used by this profile. 139 void SetPrefService( 140 std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs); 141 142 // Makes the Profile being built a guest profile. 143 void SetGuestSession(); 144 145 // Makes Profile::AllowsBrowserWindows() return false. 146 void DisallowBrowserWindows(); 147 148 // Override the default behavior of is_new_profile to return the provided 149 // value. 150 void OverrideIsNewProfile(bool is_new_profile); 151 152 // Sets the supervised user ID (which is empty by default). If it is set to 153 // a non-empty string, the profile is supervised. 154 void SetSupervisedUserId(const std::string& supervised_user_id); 155 156 #if defined(OS_CHROMEOS) 157 void SetUserCloudPolicyManagerChromeOS( 158 std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> 159 user_cloud_policy_manager); 160 #else 161 void SetUserCloudPolicyManager( 162 std::unique_ptr<policy::UserCloudPolicyManager> 163 user_cloud_policy_manager); 164 #endif // defined(OS_CHROMEOS) 165 166 // Sets the PolicyService to be used by this profile. 167 void SetPolicyService( 168 std::unique_ptr<policy::PolicyService> policy_service); 169 170 // Sets the UserProfileName to be used by this profile. 171 void SetProfileName(const std::string& profile_name); 172 173 void OverridePolicyConnectorIsManagedForTesting(bool is_managed); 174 175 // Creates the TestingProfile using previously-set settings. 176 std::unique_ptr<TestingProfile> Build(); 177 178 // Build an OffTheRecord profile, owned by |original_profile|. Note: unless 179 // you need to customize the Builder, or access TestingProfile member 180 // functions, you can use original_profile->GetOffTheRecordProfile(). 181 TestingProfile* BuildOffTheRecord(TestingProfile* original_profile, 182 const OTRProfileID& otr_profile_id); 183 184 TestingProfile* BuildIncognito(TestingProfile* original_profile); 185 186 private: 187 // If true, Build() has already been called. 188 bool build_called_; 189 190 // Various staging variables where values are held until Build() is invoked. 191 std::unique_ptr<sync_preferences::PrefServiceSyncable> pref_service_; 192 #if BUILDFLAG(ENABLE_EXTENSIONS) 193 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_; 194 #endif 195 base::FilePath path_; 196 Delegate* delegate_; 197 bool guest_session_; 198 bool allows_browser_windows_; 199 base::Optional<bool> is_new_profile_; 200 std::string supervised_user_id_; 201 #if defined(OS_CHROMEOS) 202 std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> 203 user_cloud_policy_manager_; 204 #else 205 std::unique_ptr<policy::UserCloudPolicyManager> user_cloud_policy_manager_; 206 #endif 207 std::unique_ptr<policy::PolicyService> policy_service_; 208 TestingFactories testing_factories_; 209 std::string profile_name_; 210 base::Optional<bool> override_policy_connector_is_managed_; 211 }; 212 213 // Multi-profile aware constructor that takes the path to a directory managed 214 // for this profile. This constructor is meant to be used by 215 // TestingProfileManager::CreateTestingProfile. If you need to create multi- 216 // profile profiles, use that factory method instead of this directly. 217 // Exception: if you need to create multi-profile profiles for testing the 218 // ProfileManager, then use the constructor below instead. 219 explicit TestingProfile(const base::FilePath& path); 220 221 // Multi-profile aware constructor that takes the path to a directory managed 222 // for this profile and a delegate. This constructor is meant to be used 223 // for unittesting the ProfileManager. 224 TestingProfile(const base::FilePath& path, Delegate* delegate); 225 226 // Full constructor allowing the setting of all possible instance data. 227 // Callers should use Builder::Build() instead of invoking this constructor. 228 TestingProfile( 229 const base::FilePath& path, 230 Delegate* delegate, 231 #if BUILDFLAG(ENABLE_EXTENSIONS) 232 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy, 233 #endif 234 std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs, 235 TestingProfile* parent, 236 bool guest_session, 237 bool allows_browser_windows, 238 base::Optional<bool> is_new_profile, 239 const std::string& supervised_user_id, 240 #if defined(OS_CHROMEOS) 241 std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> policy_manager, 242 #else 243 std::unique_ptr<policy::UserCloudPolicyManager> policy_manager, 244 #endif // defined(OS_CHROMEOS) 245 std::unique_ptr<policy::PolicyService> policy_service, 246 TestingFactories testing_factories, 247 const std::string& profile_name, 248 base::Optional<bool> override_policy_connector_is_managed, 249 base::Optional<OTRProfileID> otr_profile_id); 250 251 ~TestingProfile() override; 252 253 // !!!!!!!! WARNING: THIS IS GENERALLY NOT SAFE TO CALL! !!!!!!!! 254 // This bypasses the BrowserContextDependencyManager, and in particular, it 255 // destroys any previously-created HistoryService. That means any other 256 // KeyedServices that depend on HistoryService may be left with dangling 257 // pointers. 258 // Instead, use Builder::AddTestingFactory to inject your own factories. 259 // !!!!!!!! WARNING: THIS IS GENERALLY NOT SAFE TO CALL! !!!!!!!! 260 // Creates the history service. Returns true on success. 261 // TODO(crbug.com/1106699): Remove this API and adopt the Builder instead. 262 bool CreateHistoryService() WARN_UNUSED_RESULT; 263 264 // Creates a WebDataService. If not invoked, the web data service is NULL. 265 // TODO(crbug.com/1106699): Remove this API and adopt the Builder instead. 266 void CreateWebDataService(); 267 268 // Allow setting a profile as Guest after-the-fact to simplify some tests. 269 void SetGuestSession(bool guest); 270 271 // Allow setting the return value of IsNewProfile. 272 void SetIsNewProfile(bool is_new_profile); 273 274 sync_preferences::TestingPrefServiceSyncable* GetTestingPrefService(); 275 276 // Called on the parent of an OffTheRecord |otr_profile|. Usually called from 277 // the constructor of an OffTheRecord TestingProfile, but can also be used by 278 // tests to provide an OffTheRecordProfileImpl instance. 279 // |otr_profile| cannot be empty. 280 void SetOffTheRecordProfile(std::unique_ptr<Profile> otr_profile); 281 282 void SetSupervisedUserId(const std::string& id); 283 284 // content::BrowserContext 285 base::FilePath GetPath() override; 286 base::FilePath GetPath() const override; 287 base::Time GetCreationTime() const override; 288 #if !defined(OS_ANDROID) 289 std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate( 290 const base::FilePath& partition_path) override; 291 #endif // !defined(OS_ANDROID) 292 scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() override; 293 // Do not override IsOffTheRecord to turn a normal profile into an incognito 294 // profile dynamically. 295 bool IsOffTheRecord() final; 296 bool IsOffTheRecord() const final; 297 const OTRProfileID& GetOTRProfileID() const override; 298 content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; 299 content::ResourceContext* GetResourceContext() override; 300 content::BrowserPluginGuestManager* GetGuestManager() override; 301 storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; 302 content::PushMessagingService* GetPushMessagingService() override; 303 content::StorageNotificationService* GetStorageNotificationService() override; 304 content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; 305 content::PermissionControllerDelegate* GetPermissionControllerDelegate() 306 override; 307 content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate() 308 override; 309 content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override; 310 content::BackgroundSyncController* GetBackgroundSyncController() override; 311 content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate() 312 override; 313 void SetCorsOriginAccessListForOrigin( 314 const url::Origin& source_origin, 315 std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns, 316 std::vector<network::mojom::CorsOriginPatternPtr> block_patterns, 317 base::OnceClosure closure) override; 318 319 TestingProfile* AsTestingProfile() override; 320 321 // Profile 322 std::string GetProfileUserName() const override; 323 324 Profile* GetOffTheRecordProfile(const OTRProfileID& otr_profile_id) override; 325 std::vector<Profile*> GetAllOffTheRecordProfiles() override; 326 void DestroyOffTheRecordProfile(Profile* otr_profile) override; 327 bool HasOffTheRecordProfile(const OTRProfileID& otr_profile_id) override; 328 bool HasAnyOffTheRecordProfile() override; 329 Profile* GetOriginalProfile() override; 330 const Profile* GetOriginalProfile() const override; 331 bool IsSupervised() const override; 332 bool IsChild() const override; 333 bool IsLegacySupervised() const override; 334 bool AllowsBrowserWindows() const override; 335 #if BUILDFLAG(ENABLE_EXTENSIONS) 336 void SetExtensionSpecialStoragePolicy( 337 ExtensionSpecialStoragePolicy* extension_special_storage_policy); 338 #endif 339 ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() override; 340 341 PrefService* GetPrefs() override; 342 const PrefService* GetPrefs() const override; 343 #if !defined(OS_ANDROID) 344 ChromeZoomLevelPrefs* GetZoomLevelPrefs() override; 345 #endif // !defined(OS_ANDROID) 346 scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override; 347 set_last_session_exited_cleanly(bool value)348 void set_last_session_exited_cleanly(bool value) { 349 last_session_exited_cleanly_ = value; 350 } 351 bool IsSameOrParent(Profile* profile) override; 352 base::Time GetStartTime() const override; 353 ProfileKey* GetProfileKey() const override; 354 policy::SchemaRegistryService* GetPolicySchemaRegistryService() override; 355 #if defined(OS_CHROMEOS) 356 policy::UserCloudPolicyManagerChromeOS* GetUserCloudPolicyManagerChromeOS() 357 override; 358 policy::ActiveDirectoryPolicyManager* GetActiveDirectoryPolicyManager() 359 override; 360 #else 361 policy::UserCloudPolicyManager* GetUserCloudPolicyManager() override; 362 #endif // defined(OS_CHROMEOS) 363 policy::ProfilePolicyConnector* GetProfilePolicyConnector() override; 364 const policy::ProfilePolicyConnector* GetProfilePolicyConnector() 365 const override; 366 base::FilePath last_selected_directory() override; 367 void set_last_selected_directory(const base::FilePath& path) override; 368 bool WasCreatedByVersionOrLater(const std::string& version) override; 369 bool IsGuestSession() const override; 370 bool IsEphemeralGuestProfile() const override; 371 bool IsNewProfile() const override; SetExitType(ExitType exit_type)372 void SetExitType(ExitType exit_type) override {} 373 ExitType GetLastSessionExitType() const override; 374 void ConfigureNetworkContextParams( 375 bool in_memory, 376 const base::FilePath& relative_partition_path, 377 network::mojom::NetworkContextParams* network_context_params, 378 network::mojom::CertVerifierCreationParams* cert_verifier_creation_params) 379 override; 380 381 #if defined(OS_CHROMEOS) 382 void ChangeAppLocale(const std::string&, AppLocaleChangedVia) override; OnLogin()383 void OnLogin() override {} InitChromeOSPreferences()384 void InitChromeOSPreferences() override {} 385 chromeos::ScopedCrosSettingsTestHelper* ScopedCrosSettingsTestHelper(); 386 requested_locale()387 base::Optional<std::string> requested_locale() { return requested_locale_; } 388 #endif // defined(OS_CHROMEOS) 389 390 // Schedules a task on the history backend and runs a nested loop until the 391 // task is processed. This has the effect of blocking the caller until the 392 // history service processes all pending requests. 393 void BlockUntilHistoryProcessesPendingRequests(); 394 395 GURL GetHomePage() override; 396 397 void SetCreationTimeForTesting(base::Time creation_time) override; 398 399 PrefService* GetOffTheRecordPrefs() override; 400 RecordMainFrameNavigation()401 void RecordMainFrameNavigation() override {} 402 set_profile_name(const std::string & profile_name)403 void set_profile_name(const std::string& profile_name) { 404 profile_name_ = profile_name; 405 } 406 407 using ProfileDestructionCallback = base::OnceCallback<void()>; SetProfileDestructionObserver(ProfileDestructionCallback callback)408 void SetProfileDestructionObserver(ProfileDestructionCallback callback) { 409 profile_destruction_callback_ = std::move(callback); 410 } 411 412 private: 413 // Called when profile is deleted. 414 ProfileDestructionCallback profile_destruction_callback_; 415 416 protected: 417 base::Time start_time_; 418 419 // The key to index KeyedService instances created by 420 // SimpleKeyedServiceFactory. 421 std::unique_ptr<ProfileKey> key_; 422 423 std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs_; 424 // ref only for right type, lifecycle is managed by prefs_ 425 sync_preferences::TestingPrefServiceSyncable* testing_prefs_; 426 427 private: 428 // Common initialization between the two constructors. 429 void Init(); 430 431 // Finishes initialization when a profile is created asynchronously. 432 void FinishInit(); 433 434 // Creates a TestingPrefService and associates it with the TestingProfile. 435 void CreateTestingPrefService(); 436 437 #if BUILDFLAG(ENABLE_SUPERVISED_USERS) 438 // Creates a pref service that uses SupervisedUserPrefStore and associates 439 // it with the TestingProfile. 440 void CreatePrefServiceForSupervisedUser(); 441 #endif // BUILDFLAG(ENABLE_SUPERVISED_USERS) 442 443 // Initializes |prefs_| for an incognito profile, derived from 444 // |original_profile_|. 445 void CreateIncognitoPrefService(); 446 447 // Creates a ProfilePolicyConnector. 448 void CreateProfilePolicyConnector(); 449 450 std::unique_ptr<net::CookieStore, content::BrowserThread::DeleteOnIOThread> 451 extensions_cookie_store_; 452 453 std::map<OTRProfileID, std::unique_ptr<Profile>> otr_profiles_; 454 TestingProfile* original_profile_; 455 456 bool guest_session_; 457 458 bool allows_browser_windows_; 459 460 base::Optional<bool> is_new_profile_; 461 462 std::string supervised_user_id_; 463 464 // Did the last session exit cleanly? Default is true. 465 bool last_session_exited_cleanly_; 466 467 scoped_refptr<HostContentSettingsMap> host_content_settings_map_; 468 469 base::FilePath last_selected_directory_; 470 471 #if BUILDFLAG(ENABLE_EXTENSIONS) 472 scoped_refptr<ExtensionSpecialStoragePolicy> 473 extension_special_storage_policy_; 474 #endif 475 476 // The path to this profile. This will be valid in either of the two above 477 // cases. 478 base::FilePath profile_path_; 479 480 base::FilePath extensions_path_; 481 482 // We keep a weak pointer to the dependency manager we want to notify on our 483 // death. Defaults to the Singleton implementation but overridable for 484 // testing. 485 SimpleDependencyManager* simple_dependency_manager_; 486 BrowserContextDependencyManager* browser_context_dependency_manager_; 487 488 // Owned, but must be deleted on the IO thread so not placing in a 489 // std::unique_ptr<>. 490 content::MockResourceContext* resource_context_; 491 492 std::unique_ptr<policy::SchemaRegistryService> schema_registry_service_; 493 #if defined(OS_CHROMEOS) 494 std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> 495 user_cloud_policy_manager_; 496 #else 497 std::unique_ptr<policy::UserCloudPolicyManager> user_cloud_policy_manager_; 498 #endif // defined(OS_CHROMEOS) 499 std::unique_ptr<policy::ProfilePolicyConnector> profile_policy_connector_; 500 501 // Weak pointer to a delegate for indicating that a profile was created. 502 Delegate* delegate_; 503 504 std::string profile_name_; 505 506 base::Optional<bool> override_policy_connector_is_managed_; 507 base::Optional<OTRProfileID> otr_profile_id_; 508 509 #if defined(OS_CHROMEOS) 510 std::unique_ptr<chromeos::ScopedCrosSettingsTestHelper> 511 scoped_cros_settings_test_helper_; 512 513 base::Optional<std::string> requested_locale_; 514 #endif // defined(OS_CHROMEOS) 515 516 std::unique_ptr<policy::PolicyService> policy_service_; 517 518 #if BUILDFLAG(ENABLE_SUPERVISED_USERS) 519 TestingPrefStore* supervised_user_pref_store_ = nullptr; 520 #endif // BUILDFLAG(ENABLE_SUPERVISED_USERS) 521 }; 522 523 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_ 524