Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
blobd469a26d01e82a881b5eeedc4cdc2a506e7761c0
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.
5 #include "base/files/file_path.h"
6 #include "base/memory/scoped_ptr.h"
7 #include "base/prefs/pref_service.h"
8 #include "base/run_loop.h"
9 #include "base/thread_task_runner_handle.h"
10 #include "base/time/time.h"
11 #include "chrome/browser/browser_process.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
14 #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
15 #include "chrome/browser/prefs/browser_prefs.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/signin/account_fetcher_service_factory.h"
18 #include "chrome/browser/signin/chrome_signin_client_factory.h"
19 #include "chrome/browser/signin/fake_account_fetcher_service_builder.h"
20 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
21 #include "chrome/browser/signin/fake_signin_manager_builder.h"
22 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
23 #include "chrome/browser/signin/signin_manager_factory.h"
24 #include "chrome/browser/signin/test_signin_client_builder.h"
25 #include "chrome/test/base/testing_browser_process.h"
26 #include "chrome/test/base/testing_pref_service_syncable.h"
27 #include "chrome/test/base/testing_profile.h"
28 #include "components/policy/core/browser/browser_policy_connector.h"
29 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
30 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
31 #include "components/policy/core/common/cloud/mock_device_management_service.h"
32 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
33 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
34 #include "components/policy/core/common/schema_registry.h"
35 #include "components/signin/core/browser/account_tracker_service.h"
36 #include "components/signin/core/browser/fake_account_fetcher_service.h"
37 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
38 #include "components/signin/core/browser/signin_manager.h"
39 #include "content/public/browser/browser_context.h"
40 #include "content/public/browser/notification_details.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/notification_source.h"
43 #include "content/public/test/test_browser_thread_bundle.h"
44 #include "google_apis/gaia/gaia_constants.h"
45 #include "google_apis/gaia/google_service_auth_error.h"
46 #include "net/base/net_errors.h"
47 #include "net/http/http_status_code.h"
48 #include "net/url_request/test_url_fetcher_factory.h"
49 #include "net/url_request/url_request_context_getter.h"
50 #include "net/url_request/url_request_status.h"
51 #include "net/url_request/url_request_test_util.h"
52 #include "testing/gmock/include/gmock/gmock.h"
53 #include "testing/gtest/include/gtest/gtest.h"
55 #if defined(OS_ANDROID)
56 #include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
57 #else
58 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
59 #endif
61 namespace em = enterprise_management;
63 using testing::AnyNumber;
64 using testing::Mock;
65 using testing::_;
67 namespace policy {
69 namespace {
71 const char kTestGaiaId[] = "gaia-id-testuser@test.com";
72 const char kTestUser[] = "testuser@test.com";
74 #if !defined(OS_ANDROID)
75 const char kValidTokenResponse[] =
76 "{"
77 " \"access_token\": \"at1\","
78 " \"expires_in\": 3600,"
79 " \"token_type\": \"Bearer\""
80 "}";
81 #endif
83 const char kHostedDomainResponse[] =
84 "{"
85 " \"hd\": \"test.com\""
86 "}";
88 UserCloudPolicyManager* BuildCloudPolicyManager(
89 content::BrowserContext* context) {
90 MockUserCloudPolicyStore* store = new MockUserCloudPolicyStore();
91 EXPECT_CALL(*store, Load()).Times(AnyNumber());
93 return new UserCloudPolicyManager(
94 scoped_ptr<UserCloudPolicyStore>(store),
95 base::FilePath(),
96 scoped_ptr<CloudExternalDataManager>(),
97 base::ThreadTaskRunnerHandle::Get(),
98 base::ThreadTaskRunnerHandle::Get(),
99 base::ThreadTaskRunnerHandle::Get());
102 class UserPolicySigninServiceTest : public testing::Test {
103 public:
104 UserPolicySigninServiceTest()
105 : mock_store_(NULL),
106 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
107 register_completed_(false) {}
109 MOCK_METHOD1(OnPolicyRefresh, void(bool));
111 void OnRegisterCompleted(const std::string& dm_token,
112 const std::string& client_id) {
113 register_completed_ = true;
114 dm_token_ = dm_token;
115 client_id_ = client_id;
118 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
119 // Policy client registration on Android depends on Token Service having
120 // a valid login token, while on other platforms, the login refresh token
121 // is specified directly.
122 #if defined(OS_ANDROID)
123 GetTokenService()->UpdateCredentials(
124 AccountTrackerService::PickAccountIdForAccount(
125 profile_.get()->GetPrefs(), kTestGaiaId, kTestUser),
126 "oauth2_login_refresh_token");
127 #endif
128 service->RegisterForPolicy(
129 kTestUser,
130 #if !defined(OS_ANDROID)
131 "mock_oauth_token",
132 #endif
133 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
134 base::Unretained(this)));
135 ASSERT_TRUE(IsRequestActive());
138 void SetUp() override {
139 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
140 &device_management_service_);
142 local_state_.reset(new TestingPrefServiceSimple);
143 chrome::RegisterLocalState(local_state_->registry());
144 system_request_context_getter_ = new net::TestURLRequestContextGetter(
145 base::ThreadTaskRunnerHandle::Get());
146 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
147 system_request_context_getter_.get());
148 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
150 g_browser_process->browser_policy_connector()->Init(
151 local_state_.get(), system_request_context_getter_);
153 // Create a testing profile with cloud-policy-on-signin enabled, and bring
154 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
155 scoped_ptr<TestingPrefServiceSyncable> prefs(
156 new TestingPrefServiceSyncable());
157 chrome::RegisterUserProfilePrefs(prefs->registry());
159 // UserCloudPolicyManagerFactory isn't a real
160 // BrowserContextKeyedServiceFactory (it derives from
161 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
162 // instances) so we have to inject our testing factory via a special
163 // API before creating the profile.
164 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
165 BuildCloudPolicyManager);
166 TestingProfile::Builder builder;
167 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
168 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
169 BuildFakeSigninManagerBase);
170 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
171 BuildFakeProfileOAuth2TokenService);
172 builder.AddTestingFactory(AccountFetcherServiceFactory::GetInstance(),
173 FakeAccountFetcherServiceBuilder::BuildForTests);
174 builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(),
175 signin::BuildTestSigninClient);
177 profile_ = builder.Build().Pass();
178 url_factory_.set_remove_fetcher_on_delete(true);
180 signin_manager_ = static_cast<FakeSigninManager*>(
181 SigninManagerFactory::GetForProfile(profile_.get()));
182 // Tests are responsible for freeing the UserCloudPolicyManager instances
183 // they inject.
184 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
185 profile_.get()));
186 manager_->Init(&schema_registry_);
187 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
188 manager_->core()->store());
189 DCHECK(mock_store_);
190 AddProfile();
192 Mock::VerifyAndClearExpectations(mock_store_);
195 void TearDown() override {
196 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
197 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
198 // Free the profile before we clear out the browser prefs.
199 profile_.reset();
200 TestingBrowserProcess* testing_browser_process =
201 TestingBrowserProcess::GetGlobal();
202 testing_browser_process->SetLocalState(NULL);
203 local_state_.reset();
204 testing_browser_process->SetBrowserPolicyConnector(NULL);
205 base::RunLoop run_loop;
206 run_loop.RunUntilIdle();
209 virtual void AddProfile() {
210 // For this test, the user should not be signed in yet.
211 DCHECK(!signin_manager_->IsAuthenticated());
213 // Initializing UserPolicySigninService while the user is not signed in
214 // should result in the store being cleared to remove any lingering policy.
215 EXPECT_CALL(*mock_store_, Clear());
217 // Let the SigninService know that the profile has been created.
218 content::NotificationService::current()->Notify(
219 chrome::NOTIFICATION_PROFILE_ADDED,
220 content::Source<Profile>(profile_.get()),
221 content::NotificationService::NoDetails());
224 FakeProfileOAuth2TokenService* GetTokenService() {
225 ProfileOAuth2TokenService* service =
226 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
227 return static_cast<FakeProfileOAuth2TokenService*>(service);
230 bool IsRequestActive() {
231 if (!GetTokenService()->GetPendingRequests().empty())
232 return true;
233 return url_factory_.GetFetcherByID(0);
236 void MakeOAuthTokenFetchSucceed() {
237 ASSERT_TRUE(IsRequestActive());
238 #if defined(OS_ANDROID)
239 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
240 base::Time::Now());
241 #else
242 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
243 fetcher->set_response_code(net::HTTP_OK);
244 fetcher->SetResponseString(kValidTokenResponse);
245 fetcher->delegate()->OnURLFetchComplete(fetcher);
246 #endif
249 void ReportHostedDomainStatus(bool is_hosted_domain) {
250 ASSERT_TRUE(IsRequestActive());
251 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
252 fetcher->set_response_code(net::HTTP_OK);
253 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
254 fetcher->delegate()->OnURLFetchComplete(fetcher);
257 void TestSuccessfulSignin() {
258 UserPolicySigninService* signin_service =
259 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
260 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
261 RegisterPolicyClientWithCallback(signin_service);
263 // Mimic successful oauth token fetch.
264 MakeOAuthTokenFetchSucceed();
266 // When the user is from a hosted domain, this should kick off client
267 // registration.
268 MockDeviceManagementJob* register_request = NULL;
269 EXPECT_CALL(device_management_service_,
270 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
271 .WillOnce(device_management_service_.CreateAsyncJob(
272 &register_request));
273 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
274 .Times(1);
276 // Now mimic the user being a hosted domain - this should cause a Register()
277 // call.
278 ReportHostedDomainStatus(true);
280 // Should have no more outstanding requests.
281 ASSERT_FALSE(IsRequestActive());
282 Mock::VerifyAndClearExpectations(this);
283 ASSERT_TRUE(register_request);
285 // Mimic successful client registration - this should register the client
286 // and invoke the callback.
287 em::DeviceManagementResponse registration_blob;
288 std::string expected_dm_token = "dm_token";
289 registration_blob.mutable_register_response()->set_device_management_token(
290 expected_dm_token);
291 registration_blob.mutable_register_response()->set_enrollment_type(
292 em::DeviceRegisterResponse::ENTERPRISE);
293 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
295 // UserCloudPolicyManager should not be initialized yet.
296 ASSERT_FALSE(manager_->core()->service());
297 EXPECT_TRUE(register_completed_);
298 EXPECT_EQ(dm_token_, expected_dm_token);
300 // Now call to fetch policy - this should fire off a fetch request.
301 MockDeviceManagementJob* fetch_request = NULL;
302 EXPECT_CALL(device_management_service_,
303 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
304 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
305 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
306 .Times(1);
308 signin_service->FetchPolicyForSignedInUser(
309 kTestUser,
310 dm_token_,
311 client_id_,
312 profile_->GetRequestContext(),
313 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
314 base::Unretained(this)));
316 Mock::VerifyAndClearExpectations(this);
317 ASSERT_TRUE(fetch_request);
319 // UserCloudPolicyManager should now be initialized.
320 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
321 ASSERT_TRUE(manager_->core()->service());
323 // Make the policy fetch succeed - this should result in a write to the
324 // store and ultimately result in a call to OnPolicyRefresh().
325 EXPECT_CALL(*mock_store_, Store(_));
326 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
328 // Create a fake policy blob to deliver to the client.
329 em::DeviceManagementResponse policy_blob;
330 em::PolicyData policy_data;
331 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
332 em::PolicyFetchResponse* policy_response =
333 policy_blob.mutable_policy_response()->add_response();
334 ASSERT_TRUE(policy_data.SerializeToString(
335 policy_response->mutable_policy_data()));
336 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
338 // Complete the store which should cause the policy fetch callback to be
339 // invoked.
340 mock_store_->NotifyStoreLoaded();
341 Mock::VerifyAndClearExpectations(this);
344 scoped_ptr<TestingProfile> profile_;
345 MockUserCloudPolicyStore* mock_store_; // Not owned.
346 SchemaRegistry schema_registry_;
347 scoped_ptr<UserCloudPolicyManager> manager_;
349 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
350 // various components asynchronously via tasks, so create fake threads here.
351 content::TestBrowserThreadBundle thread_bundle_;
353 net::TestURLFetcherFactory url_factory_;
355 FakeSigninManager* signin_manager_;
357 // Used in conjunction with OnRegisterCompleted() to test client registration
358 // callbacks.
359 std::string dm_token_;
360 std::string client_id_;
362 // True if OnRegisterCompleted() was called.
363 bool register_completed_;
365 // Weak ptr to the MockDeviceManagementService (object is owned by the
366 // BrowserPolicyConnector).
367 MockDeviceManagementService device_management_service_;
369 scoped_ptr<TestingPrefServiceSimple> local_state_;
370 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
373 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
374 public:
375 void AddProfile() override {
376 // UserCloudPolicyManager should not be initialized.
377 ASSERT_FALSE(manager_->core()->service());
379 // Set the user as signed in.
380 SigninManagerFactory::GetForProfile(profile_.get())->
381 SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
383 // Let the SigninService know that the profile has been created.
384 content::NotificationService::current()->Notify(
385 chrome::NOTIFICATION_PROFILE_ADDED,
386 content::Source<Profile>(profile_.get()),
387 content::NotificationService::NoDetails());
391 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
392 // Make sure user is not signed in.
393 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
394 IsAuthenticated());
396 // UserCloudPolicyManager should not be initialized.
397 ASSERT_FALSE(manager_->core()->service());
400 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
401 // token after signin. Revisit this after figuring how to handle that on
402 // Android.
403 #if !defined(OS_ANDROID)
405 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
406 // UserCloudPolicyManager should be initialized.
407 ASSERT_TRUE(manager_->core()->service());
409 // Complete initialization of the store.
410 mock_store_->NotifyStoreLoaded();
412 // No oauth access token yet, so client registration should be deferred.
413 ASSERT_FALSE(IsRequestActive());
415 // Make oauth token available.
416 GetTokenService()->UpdateCredentials(
417 SigninManagerFactory::GetForProfile(profile_.get())
418 ->GetAuthenticatedAccountId(),
419 "oauth_login_refresh_token");
421 // Client registration should be in progress since we now have an oauth token.
422 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
423 ASSERT_TRUE(IsRequestActive());
426 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
427 // UserCloudPolicyManager should be initialized.
428 ASSERT_TRUE(manager_->core()->service());
430 // Complete initialization of the store.
431 mock_store_->NotifyStoreLoaded();
433 // No oauth access token yet, so client registration should be deferred.
434 ASSERT_FALSE(IsRequestActive());
436 // Make oauth token available.
437 GetTokenService()->UpdateCredentials(
438 SigninManagerFactory::GetForProfile(profile_.get())
439 ->GetAuthenticatedAccountId(),
440 "oauth_login_refresh_token");
442 // Client registration should be in progress since we now have an oauth token.
443 ASSERT_TRUE(IsRequestActive());
445 // Now fail the access token fetch.
446 GoogleServiceAuthError error(
447 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
448 GetTokenService()->IssueErrorForAllPendingRequests(error);
449 ASSERT_FALSE(IsRequestActive());
452 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
453 // UserCloudPolicyManager should not be initialized since there is no
454 // signed-in user.
455 ASSERT_FALSE(manager_->core()->service());
457 // Now sign in the user.
458 SigninManagerFactory::GetForProfile(profile_.get())
459 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
461 // Complete initialization of the store.
462 mock_store_->NotifyStoreLoaded();
464 // Make oauth token available.
465 GetTokenService()->UpdateCredentials(
466 SigninManagerFactory::GetForProfile(profile_.get())
467 ->GetAuthenticatedAccountId(),
468 "oauth_login_refresh_token");
470 // UserCloudPolicyManager should be initialized.
471 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
472 ASSERT_TRUE(manager_->core()->service());
474 // Client registration should be in progress since we have an oauth token.
475 ASSERT_TRUE(IsRequestActive());
478 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
479 // UserCloudPolicyManager should not be initialized since there is no
480 // signed-in user.
481 ASSERT_FALSE(manager_->core()->service());
483 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
484 SigninManagerFactory::GetForProfile(profile_.get())
485 ->SetAuthenticatedAccountInfo("gaia-id-non_enterprise_user@gmail.com",
486 "non_enterprise_user@gmail.com");
488 // Complete initialization of the store.
489 mock_store_->NotifyStoreLoaded();
491 // Make oauth token available.
492 GetTokenService()->UpdateCredentials(
493 SigninManagerFactory::GetForProfile(profile_.get())
494 ->GetAuthenticatedAccountId(),
495 "oauth_login_refresh_token");
497 // UserCloudPolicyManager should not be initialized and there should be no
498 // DMToken request active.
499 ASSERT_TRUE(!manager_->core()->service());
500 ASSERT_FALSE(IsRequestActive());
503 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
504 // UserCloudPolicyManager should not be initialized since there is no
505 // signed-in user.
506 ASSERT_FALSE(manager_->core()->service());
508 // Now sign in the user.
509 SigninManagerFactory::GetForProfile(profile_.get())
510 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
512 // Make oauth token available.
513 GetTokenService()->UpdateCredentials(
514 SigninManagerFactory::GetForProfile(profile_.get())
515 ->GetAuthenticatedAccountId(),
516 "oauth_login_refresh_token");
518 // UserCloudPolicyManager should be initialized.
519 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
520 ASSERT_TRUE(manager_->core()->service());
522 // Client registration should not be in progress since the store is not
523 // yet initialized.
524 ASSERT_FALSE(IsRequestActive());
526 // Complete initialization of the store with no policy (unregistered client).
527 mock_store_->NotifyStoreLoaded();
529 // Client registration should be in progress since we have an oauth token.
530 ASSERT_TRUE(IsRequestActive());
533 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
534 // UserCloudPolicyManager should not be initialized since there is no
535 // signed-in user.
536 ASSERT_FALSE(manager_->core()->service());
538 // Now sign in the user.
539 SigninManagerFactory::GetForProfile(profile_.get())
540 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
542 // Make oauth token available.
543 GetTokenService()->UpdateCredentials(
544 SigninManagerFactory::GetForProfile(profile_.get())
545 ->GetAuthenticatedAccountId(),
546 "oauth_login_refresh_token");
548 // UserCloudPolicyManager should be initialized.
549 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
550 ASSERT_TRUE(manager_->core()->service());
552 // Client registration should not be in progress since the store is not
553 // yet initialized.
554 ASSERT_FALSE(manager_->IsClientRegistered());
555 ASSERT_FALSE(IsRequestActive());
557 mock_store_->policy_.reset(new enterprise_management::PolicyData());
558 mock_store_->policy_->set_request_token("fake token");
559 mock_store_->policy_->set_device_id("fake client id");
561 // Complete initialization of the store.
562 mock_store_->NotifyStoreLoaded();
564 // Client registration should not be in progress since the client should be
565 // already registered.
566 ASSERT_TRUE(manager_->IsClientRegistered());
567 ASSERT_FALSE(IsRequestActive());
570 #endif // !defined(OS_ANDROID)
572 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
573 // UserCloudPolicyManager should be initialized.
574 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
575 ASSERT_TRUE(manager_->core()->service());
577 // Signing out will clear the policy from the store.
578 EXPECT_CALL(*mock_store_, Clear());
580 // Now sign out.
581 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
582 signin_metrics::SIGNOUT_TEST);
584 // UserCloudPolicyManager should be shut down.
585 ASSERT_FALSE(manager_->core()->service());
588 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
589 UserPolicySigninService* signin_service =
590 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
591 RegisterPolicyClientWithCallback(signin_service);
592 Mock::VerifyAndClearExpectations(this);
594 // UserCloudPolicyManager should not be initialized.
595 ASSERT_FALSE(manager_->core()->service());
596 ASSERT_TRUE(IsRequestActive());
597 EXPECT_FALSE(register_completed_);
599 // Cause the access token fetch to fail - callback should be invoked.
600 #if defined(OS_ANDROID)
601 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
602 GetTokenService()->IssueErrorForAllPendingRequests(
603 GoogleServiceAuthError::FromServiceError("fail"));
604 #else
605 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
606 fetcher->set_status(net::URLRequestStatus::FromError(net::ERR_FAILED));
607 fetcher->delegate()->OnURLFetchComplete(fetcher);
608 #endif
610 EXPECT_TRUE(register_completed_);
611 EXPECT_TRUE(dm_token_.empty());
612 EXPECT_FALSE(IsRequestActive());
615 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
616 UserPolicySigninService* signin_service =
617 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
618 RegisterPolicyClientWithCallback(signin_service);
620 // UserCloudPolicyManager should not be initialized.
621 ASSERT_FALSE(manager_->core()->service());
622 ASSERT_TRUE(IsRequestActive());
624 // Cause the access token request to succeed.
625 MakeOAuthTokenFetchSucceed();
627 // Should be a follow-up fetch to check the hosted-domain status.
628 ASSERT_TRUE(IsRequestActive());
629 Mock::VerifyAndClearExpectations(this);
631 EXPECT_FALSE(register_completed_);
633 // Report that the user is not on a hosted domain - callback should be
634 // invoked reporting a failed fetch.
635 ReportHostedDomainStatus(false);
637 // Since this is not a hosted domain, we should not issue a request for a
638 // DMToken.
639 EXPECT_TRUE(register_completed_);
640 EXPECT_TRUE(dm_token_.empty());
641 ASSERT_FALSE(IsRequestActive());
644 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
645 UserPolicySigninService* signin_service =
646 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
647 RegisterPolicyClientWithCallback(signin_service);
649 // UserCloudPolicyManager should not be initialized.
650 ASSERT_FALSE(manager_->core()->service());
652 // Mimic successful oauth token fetch.
653 MakeOAuthTokenFetchSucceed();
655 EXPECT_FALSE(register_completed_);
657 // When the user is from a hosted domain, this should kick off client
658 // registration.
659 MockDeviceManagementJob* register_request = NULL;
660 EXPECT_CALL(device_management_service_,
661 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
662 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
663 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
664 .Times(1);
666 // Now mimic the user being a hosted domain - this should cause a Register()
667 // call.
668 ReportHostedDomainStatus(true);
670 // Should have no more outstanding requests.
671 ASSERT_FALSE(IsRequestActive());
672 Mock::VerifyAndClearExpectations(this);
673 ASSERT_TRUE(register_request);
674 EXPECT_FALSE(register_completed_);
676 // Make client registration fail (hosted domain user that is not managed).
677 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
678 em::DeviceManagementResponse());
679 EXPECT_TRUE(register_completed_);
680 EXPECT_TRUE(dm_token_.empty());
683 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
684 UserPolicySigninService* signin_service =
685 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
686 RegisterPolicyClientWithCallback(signin_service);
688 // Mimic successful oauth token fetch.
689 MakeOAuthTokenFetchSucceed();
691 // When the user is from a hosted domain, this should kick off client
692 // registration.
693 MockDeviceManagementJob* register_request = NULL;
694 EXPECT_CALL(device_management_service_,
695 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
696 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
697 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
698 .Times(1);
700 // Now mimic the user being a hosted domain - this should cause a Register()
701 // call.
702 ReportHostedDomainStatus(true);
704 // Should have no more outstanding requests.
705 ASSERT_FALSE(IsRequestActive());
706 Mock::VerifyAndClearExpectations(this);
707 ASSERT_TRUE(register_request);
708 EXPECT_FALSE(register_completed_);
710 em::DeviceManagementResponse registration_blob;
711 std::string expected_dm_token = "dm_token";
712 registration_blob.mutable_register_response()->set_device_management_token(
713 expected_dm_token);
714 registration_blob.mutable_register_response()->set_enrollment_type(
715 em::DeviceRegisterResponse::ENTERPRISE);
716 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
717 Mock::VerifyAndClearExpectations(this);
718 EXPECT_TRUE(register_completed_);
719 EXPECT_EQ(dm_token_, expected_dm_token);
720 // UserCloudPolicyManager should not be initialized.
721 ASSERT_FALSE(manager_->core()->service());
724 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
725 // Initiate a policy fetch request.
726 MockDeviceManagementJob* fetch_request = NULL;
727 EXPECT_CALL(device_management_service_,
728 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
729 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
730 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
731 .Times(1);
732 UserPolicySigninService* signin_service =
733 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
734 signin_service->FetchPolicyForSignedInUser(
735 kTestUser,
736 "mock_dm_token",
737 "mock_client_id",
738 profile_->GetRequestContext(),
739 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
740 base::Unretained(this)));
741 ASSERT_TRUE(fetch_request);
743 // Make the policy fetch fail.
744 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
745 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
746 em::DeviceManagementResponse());
748 // UserCloudPolicyManager should be initialized.
749 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
750 ASSERT_TRUE(manager_->core()->service());
753 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
754 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
757 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
758 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
760 EXPECT_CALL(*mock_store_, Clear());
761 signin_manager_->ForceSignOut();
762 ASSERT_FALSE(manager_->core()->service());
764 // Now sign in again.
765 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
768 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
769 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
771 ASSERT_TRUE(manager_->IsClientRegistered());
773 // Kick off another policy fetch.
774 MockDeviceManagementJob* fetch_request = NULL;
775 EXPECT_CALL(device_management_service_,
776 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
777 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
778 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
779 .Times(1);
780 manager_->RefreshPolicies();
781 Mock::VerifyAndClearExpectations(this);
783 // Now, fake a transient error from the server on this policy fetch. This
784 // should have no impact on the cached policy.
785 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
786 em::DeviceManagementResponse());
787 base::RunLoop().RunUntilIdle();
788 ASSERT_TRUE(manager_->IsClientRegistered());
791 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
792 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
794 EXPECT_TRUE(manager_->IsClientRegistered());
795 #if !defined(OS_ANDROID)
796 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
797 #endif
799 // Kick off another policy fetch.
800 MockDeviceManagementJob* fetch_request = NULL;
801 EXPECT_CALL(device_management_service_,
802 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
803 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
804 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
805 .Times(1);
806 manager_->RefreshPolicies();
807 Mock::VerifyAndClearExpectations(this);
809 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
810 // indicates that chrome management is disabled and will result in the cached
811 // policy being removed and the manager shut down.
812 EXPECT_CALL(*mock_store_, Clear());
813 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
814 em::DeviceManagementResponse());
815 base::RunLoop().RunUntilIdle();
816 EXPECT_FALSE(manager_->IsClientRegistered());
817 #if !defined(OS_ANDROID)
818 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
819 #endif
822 } // namespace
824 } // namespace policy