Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
blob3295fc7ca66096331b91a0aad28c3d553e7bf087
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_profile.h"
27 #include "components/policy/core/browser/browser_policy_connector.h"
28 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
29 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
30 #include "components/policy/core/common/cloud/mock_device_management_service.h"
31 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
32 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
33 #include "components/policy/core/common/schema_registry.h"
34 #include "components/signin/core/browser/account_tracker_service.h"
35 #include "components/signin/core/browser/fake_account_fetcher_service.h"
36 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
37 #include "components/signin/core/browser/signin_manager.h"
38 #include "components/syncable_prefs/testing_pref_service_syncable.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 kTestGaiaId,
132 #else
133 "mock_oauth_token",
134 #endif
135 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
136 base::Unretained(this)));
137 ASSERT_TRUE(IsRequestActive());
140 void SetUp() override {
141 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
142 &device_management_service_);
144 local_state_.reset(new TestingPrefServiceSimple);
145 chrome::RegisterLocalState(local_state_->registry());
146 system_request_context_getter_ = new net::TestURLRequestContextGetter(
147 base::ThreadTaskRunnerHandle::Get());
148 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
149 system_request_context_getter_.get());
150 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
152 g_browser_process->browser_policy_connector()->Init(
153 local_state_.get(), system_request_context_getter_);
155 // Create a testing profile with cloud-policy-on-signin enabled, and bring
156 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
157 scoped_ptr<syncable_prefs::TestingPrefServiceSyncable> prefs(
158 new syncable_prefs::TestingPrefServiceSyncable());
159 chrome::RegisterUserProfilePrefs(prefs->registry());
161 // UserCloudPolicyManagerFactory isn't a real
162 // BrowserContextKeyedServiceFactory (it derives from
163 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
164 // instances) so we have to inject our testing factory via a special
165 // API before creating the profile.
166 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
167 BuildCloudPolicyManager);
168 TestingProfile::Builder builder;
169 builder.SetPrefService(
170 scoped_ptr<syncable_prefs::PrefServiceSyncable>(prefs.Pass()));
171 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
172 BuildFakeSigninManagerBase);
173 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
174 BuildFakeProfileOAuth2TokenService);
175 builder.AddTestingFactory(AccountFetcherServiceFactory::GetInstance(),
176 FakeAccountFetcherServiceBuilder::BuildForTests);
177 builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(),
178 signin::BuildTestSigninClient);
180 profile_ = builder.Build().Pass();
181 url_factory_.set_remove_fetcher_on_delete(true);
183 signin_manager_ = static_cast<FakeSigninManager*>(
184 SigninManagerFactory::GetForProfile(profile_.get()));
185 // Tests are responsible for freeing the UserCloudPolicyManager instances
186 // they inject.
187 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
188 profile_.get()));
189 manager_->Init(&schema_registry_);
190 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
191 manager_->core()->store());
192 DCHECK(mock_store_);
193 AddProfile();
195 Mock::VerifyAndClearExpectations(mock_store_);
198 void TearDown() override {
199 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
200 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
201 // Free the profile before we clear out the browser prefs.
202 profile_.reset();
203 TestingBrowserProcess* testing_browser_process =
204 TestingBrowserProcess::GetGlobal();
205 testing_browser_process->SetLocalState(NULL);
206 local_state_.reset();
207 testing_browser_process->ShutdownBrowserPolicyConnector();
208 base::RunLoop run_loop;
209 run_loop.RunUntilIdle();
212 virtual void AddProfile() {
213 // For this test, the user should not be signed in yet.
214 DCHECK(!signin_manager_->IsAuthenticated());
216 // Initializing UserPolicySigninService while the user is not signed in
217 // should result in the store being cleared to remove any lingering policy.
218 EXPECT_CALL(*mock_store_, Clear());
220 // Let the SigninService know that the profile has been created.
221 content::NotificationService::current()->Notify(
222 chrome::NOTIFICATION_PROFILE_ADDED,
223 content::Source<Profile>(profile_.get()),
224 content::NotificationService::NoDetails());
227 FakeProfileOAuth2TokenService* GetTokenService() {
228 ProfileOAuth2TokenService* service =
229 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
230 return static_cast<FakeProfileOAuth2TokenService*>(service);
233 bool IsRequestActive() {
234 if (!GetTokenService()->GetPendingRequests().empty())
235 return true;
236 return url_factory_.GetFetcherByID(0);
239 void MakeOAuthTokenFetchSucceed() {
240 ASSERT_TRUE(IsRequestActive());
241 #if defined(OS_ANDROID)
242 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
243 base::Time::Now());
244 #else
245 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
246 fetcher->set_response_code(net::HTTP_OK);
247 fetcher->SetResponseString(kValidTokenResponse);
248 fetcher->delegate()->OnURLFetchComplete(fetcher);
249 #endif
252 void ReportHostedDomainStatus(bool is_hosted_domain) {
253 ASSERT_TRUE(IsRequestActive());
254 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
255 fetcher->set_response_code(net::HTTP_OK);
256 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
257 fetcher->delegate()->OnURLFetchComplete(fetcher);
260 void TestSuccessfulSignin() {
261 UserPolicySigninService* signin_service =
262 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
263 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
264 RegisterPolicyClientWithCallback(signin_service);
266 // Mimic successful oauth token fetch.
267 MakeOAuthTokenFetchSucceed();
269 // When the user is from a hosted domain, this should kick off client
270 // registration.
271 MockDeviceManagementJob* register_request = NULL;
272 EXPECT_CALL(device_management_service_,
273 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
274 .WillOnce(device_management_service_.CreateAsyncJob(
275 &register_request));
276 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
277 .Times(1);
279 // Now mimic the user being a hosted domain - this should cause a Register()
280 // call.
281 ReportHostedDomainStatus(true);
283 // Should have no more outstanding requests.
284 ASSERT_FALSE(IsRequestActive());
285 Mock::VerifyAndClearExpectations(this);
286 ASSERT_TRUE(register_request);
288 // Mimic successful client registration - this should register the client
289 // and invoke the callback.
290 em::DeviceManagementResponse registration_blob;
291 std::string expected_dm_token = "dm_token";
292 registration_blob.mutable_register_response()->set_device_management_token(
293 expected_dm_token);
294 registration_blob.mutable_register_response()->set_enrollment_type(
295 em::DeviceRegisterResponse::ENTERPRISE);
296 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
298 // UserCloudPolicyManager should not be initialized yet.
299 ASSERT_FALSE(manager_->core()->service());
300 EXPECT_TRUE(register_completed_);
301 EXPECT_EQ(dm_token_, expected_dm_token);
303 // Now call to fetch policy - this should fire off a fetch request.
304 MockDeviceManagementJob* fetch_request = NULL;
305 EXPECT_CALL(device_management_service_,
306 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
307 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
308 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
309 .Times(1);
311 signin_service->FetchPolicyForSignedInUser(
312 kTestUser,
313 dm_token_,
314 client_id_,
315 profile_->GetRequestContext(),
316 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
317 base::Unretained(this)));
319 Mock::VerifyAndClearExpectations(this);
320 ASSERT_TRUE(fetch_request);
322 // UserCloudPolicyManager should now be initialized.
323 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
324 ASSERT_TRUE(manager_->core()->service());
326 // Make the policy fetch succeed - this should result in a write to the
327 // store and ultimately result in a call to OnPolicyRefresh().
328 EXPECT_CALL(*mock_store_, Store(_));
329 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
331 // Create a fake policy blob to deliver to the client.
332 em::DeviceManagementResponse policy_blob;
333 em::PolicyData policy_data;
334 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
335 em::PolicyFetchResponse* policy_response =
336 policy_blob.mutable_policy_response()->add_response();
337 ASSERT_TRUE(policy_data.SerializeToString(
338 policy_response->mutable_policy_data()));
339 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
341 // Complete the store which should cause the policy fetch callback to be
342 // invoked.
343 mock_store_->NotifyStoreLoaded();
344 Mock::VerifyAndClearExpectations(this);
347 scoped_ptr<TestingProfile> profile_;
348 MockUserCloudPolicyStore* mock_store_; // Not owned.
349 SchemaRegistry schema_registry_;
350 scoped_ptr<UserCloudPolicyManager> manager_;
352 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
353 // various components asynchronously via tasks, so create fake threads here.
354 content::TestBrowserThreadBundle thread_bundle_;
356 net::TestURLFetcherFactory url_factory_;
358 FakeSigninManager* signin_manager_;
360 // Used in conjunction with OnRegisterCompleted() to test client registration
361 // callbacks.
362 std::string dm_token_;
363 std::string client_id_;
365 // True if OnRegisterCompleted() was called.
366 bool register_completed_;
368 // Weak ptr to the MockDeviceManagementService (object is owned by the
369 // BrowserPolicyConnector).
370 MockDeviceManagementService device_management_service_;
372 scoped_ptr<TestingPrefServiceSimple> local_state_;
373 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
376 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
377 public:
378 void AddProfile() override {
379 // UserCloudPolicyManager should not be initialized.
380 ASSERT_FALSE(manager_->core()->service());
382 // Set the user as signed in.
383 SigninManagerFactory::GetForProfile(profile_.get())->
384 SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
386 // Let the SigninService know that the profile has been created.
387 content::NotificationService::current()->Notify(
388 chrome::NOTIFICATION_PROFILE_ADDED,
389 content::Source<Profile>(profile_.get()),
390 content::NotificationService::NoDetails());
394 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
395 // Make sure user is not signed in.
396 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
397 IsAuthenticated());
399 // UserCloudPolicyManager should not be initialized.
400 ASSERT_FALSE(manager_->core()->service());
403 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
404 // token after signin. Revisit this after figuring how to handle that on
405 // Android.
406 #if !defined(OS_ANDROID)
408 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
409 // UserCloudPolicyManager should be initialized.
410 ASSERT_TRUE(manager_->core()->service());
412 // Complete initialization of the store.
413 mock_store_->NotifyStoreLoaded();
415 // No oauth access token yet, so client registration should be deferred.
416 ASSERT_FALSE(IsRequestActive());
418 // Make oauth token available.
419 GetTokenService()->UpdateCredentials(
420 SigninManagerFactory::GetForProfile(profile_.get())
421 ->GetAuthenticatedAccountId(),
422 "oauth_login_refresh_token");
424 // Client registration should be in progress since we now have an oauth token.
425 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
426 ASSERT_TRUE(IsRequestActive());
429 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
430 // UserCloudPolicyManager should be initialized.
431 ASSERT_TRUE(manager_->core()->service());
433 // Complete initialization of the store.
434 mock_store_->NotifyStoreLoaded();
436 // No oauth access token yet, so client registration should be deferred.
437 ASSERT_FALSE(IsRequestActive());
439 // Make oauth token available.
440 GetTokenService()->UpdateCredentials(
441 SigninManagerFactory::GetForProfile(profile_.get())
442 ->GetAuthenticatedAccountId(),
443 "oauth_login_refresh_token");
445 // Client registration should be in progress since we now have an oauth token.
446 ASSERT_TRUE(IsRequestActive());
448 // Now fail the access token fetch.
449 GoogleServiceAuthError error(
450 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
451 GetTokenService()->IssueErrorForAllPendingRequests(error);
452 ASSERT_FALSE(IsRequestActive());
455 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
456 // UserCloudPolicyManager should not be initialized since there is no
457 // signed-in user.
458 ASSERT_FALSE(manager_->core()->service());
460 // Now sign in the user.
461 SigninManagerFactory::GetForProfile(profile_.get())
462 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
464 // Complete initialization of the store.
465 mock_store_->NotifyStoreLoaded();
467 // Make oauth token available.
468 GetTokenService()->UpdateCredentials(
469 SigninManagerFactory::GetForProfile(profile_.get())
470 ->GetAuthenticatedAccountId(),
471 "oauth_login_refresh_token");
473 // UserCloudPolicyManager should be initialized.
474 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
475 ASSERT_TRUE(manager_->core()->service());
477 // Client registration should be in progress since we have an oauth token.
478 ASSERT_TRUE(IsRequestActive());
481 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
482 // UserCloudPolicyManager should not be initialized since there is no
483 // signed-in user.
484 ASSERT_FALSE(manager_->core()->service());
486 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
487 SigninManagerFactory::GetForProfile(profile_.get())
488 ->SetAuthenticatedAccountInfo("gaia-id-non_enterprise_user@gmail.com",
489 "non_enterprise_user@gmail.com");
491 // Complete initialization of the store.
492 mock_store_->NotifyStoreLoaded();
494 // Make oauth token available.
495 GetTokenService()->UpdateCredentials(
496 SigninManagerFactory::GetForProfile(profile_.get())
497 ->GetAuthenticatedAccountId(),
498 "oauth_login_refresh_token");
500 // UserCloudPolicyManager should not be initialized and there should be no
501 // DMToken request active.
502 ASSERT_TRUE(!manager_->core()->service());
503 ASSERT_FALSE(IsRequestActive());
506 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
507 // UserCloudPolicyManager should not be initialized since there is no
508 // signed-in user.
509 ASSERT_FALSE(manager_->core()->service());
511 // Now sign in the user.
512 SigninManagerFactory::GetForProfile(profile_.get())
513 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
515 // Make oauth token available.
516 GetTokenService()->UpdateCredentials(
517 SigninManagerFactory::GetForProfile(profile_.get())
518 ->GetAuthenticatedAccountId(),
519 "oauth_login_refresh_token");
521 // UserCloudPolicyManager should be initialized.
522 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
523 ASSERT_TRUE(manager_->core()->service());
525 // Client registration should not be in progress since the store is not
526 // yet initialized.
527 ASSERT_FALSE(IsRequestActive());
529 // Complete initialization of the store with no policy (unregistered client).
530 mock_store_->NotifyStoreLoaded();
532 // Client registration should be in progress since we have an oauth token.
533 ASSERT_TRUE(IsRequestActive());
536 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
537 // UserCloudPolicyManager should not be initialized since there is no
538 // signed-in user.
539 ASSERT_FALSE(manager_->core()->service());
541 // Now sign in the user.
542 SigninManagerFactory::GetForProfile(profile_.get())
543 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
545 // Make oauth token available.
546 GetTokenService()->UpdateCredentials(
547 SigninManagerFactory::GetForProfile(profile_.get())
548 ->GetAuthenticatedAccountId(),
549 "oauth_login_refresh_token");
551 // UserCloudPolicyManager should be initialized.
552 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
553 ASSERT_TRUE(manager_->core()->service());
555 // Client registration should not be in progress since the store is not
556 // yet initialized.
557 ASSERT_FALSE(manager_->IsClientRegistered());
558 ASSERT_FALSE(IsRequestActive());
560 mock_store_->policy_.reset(new enterprise_management::PolicyData());
561 mock_store_->policy_->set_request_token("fake token");
562 mock_store_->policy_->set_device_id("fake client id");
564 // Complete initialization of the store.
565 mock_store_->NotifyStoreLoaded();
567 // Client registration should not be in progress since the client should be
568 // already registered.
569 ASSERT_TRUE(manager_->IsClientRegistered());
570 ASSERT_FALSE(IsRequestActive());
573 #endif // !defined(OS_ANDROID)
575 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
576 // UserCloudPolicyManager should be initialized.
577 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
578 ASSERT_TRUE(manager_->core()->service());
580 // Signing out will clear the policy from the store.
581 EXPECT_CALL(*mock_store_, Clear());
583 // Now sign out.
584 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
585 signin_metrics::SIGNOUT_TEST);
587 // UserCloudPolicyManager should be shut down.
588 ASSERT_FALSE(manager_->core()->service());
591 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
592 UserPolicySigninService* signin_service =
593 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
594 RegisterPolicyClientWithCallback(signin_service);
595 Mock::VerifyAndClearExpectations(this);
597 // UserCloudPolicyManager should not be initialized.
598 ASSERT_FALSE(manager_->core()->service());
599 ASSERT_TRUE(IsRequestActive());
600 EXPECT_FALSE(register_completed_);
602 // Cause the access token fetch to fail - callback should be invoked.
603 #if defined(OS_ANDROID)
604 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
605 GetTokenService()->IssueErrorForAllPendingRequests(
606 GoogleServiceAuthError::FromServiceError("fail"));
607 #else
608 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
609 fetcher->set_status(net::URLRequestStatus::FromError(net::ERR_FAILED));
610 fetcher->delegate()->OnURLFetchComplete(fetcher);
611 #endif
613 EXPECT_TRUE(register_completed_);
614 EXPECT_TRUE(dm_token_.empty());
615 EXPECT_FALSE(IsRequestActive());
618 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
619 UserPolicySigninService* signin_service =
620 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
621 RegisterPolicyClientWithCallback(signin_service);
623 // UserCloudPolicyManager should not be initialized.
624 ASSERT_FALSE(manager_->core()->service());
625 ASSERT_TRUE(IsRequestActive());
627 // Cause the access token request to succeed.
628 MakeOAuthTokenFetchSucceed();
630 // Should be a follow-up fetch to check the hosted-domain status.
631 ASSERT_TRUE(IsRequestActive());
632 Mock::VerifyAndClearExpectations(this);
634 EXPECT_FALSE(register_completed_);
636 // Report that the user is not on a hosted domain - callback should be
637 // invoked reporting a failed fetch.
638 ReportHostedDomainStatus(false);
640 // Since this is not a hosted domain, we should not issue a request for a
641 // DMToken.
642 EXPECT_TRUE(register_completed_);
643 EXPECT_TRUE(dm_token_.empty());
644 ASSERT_FALSE(IsRequestActive());
647 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
648 UserPolicySigninService* signin_service =
649 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
650 RegisterPolicyClientWithCallback(signin_service);
652 // UserCloudPolicyManager should not be initialized.
653 ASSERT_FALSE(manager_->core()->service());
655 // Mimic successful oauth token fetch.
656 MakeOAuthTokenFetchSucceed();
658 EXPECT_FALSE(register_completed_);
660 // When the user is from a hosted domain, this should kick off client
661 // registration.
662 MockDeviceManagementJob* register_request = NULL;
663 EXPECT_CALL(device_management_service_,
664 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
665 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
666 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
667 .Times(1);
669 // Now mimic the user being a hosted domain - this should cause a Register()
670 // call.
671 ReportHostedDomainStatus(true);
673 // Should have no more outstanding requests.
674 ASSERT_FALSE(IsRequestActive());
675 Mock::VerifyAndClearExpectations(this);
676 ASSERT_TRUE(register_request);
677 EXPECT_FALSE(register_completed_);
679 // Make client registration fail (hosted domain user that is not managed).
680 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
681 em::DeviceManagementResponse());
682 EXPECT_TRUE(register_completed_);
683 EXPECT_TRUE(dm_token_.empty());
686 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
687 UserPolicySigninService* signin_service =
688 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
689 RegisterPolicyClientWithCallback(signin_service);
691 // Mimic successful oauth token fetch.
692 MakeOAuthTokenFetchSucceed();
694 // When the user is from a hosted domain, this should kick off client
695 // registration.
696 MockDeviceManagementJob* register_request = NULL;
697 EXPECT_CALL(device_management_service_,
698 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
699 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
700 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
701 .Times(1);
703 // Now mimic the user being a hosted domain - this should cause a Register()
704 // call.
705 ReportHostedDomainStatus(true);
707 // Should have no more outstanding requests.
708 ASSERT_FALSE(IsRequestActive());
709 Mock::VerifyAndClearExpectations(this);
710 ASSERT_TRUE(register_request);
711 EXPECT_FALSE(register_completed_);
713 em::DeviceManagementResponse registration_blob;
714 std::string expected_dm_token = "dm_token";
715 registration_blob.mutable_register_response()->set_device_management_token(
716 expected_dm_token);
717 registration_blob.mutable_register_response()->set_enrollment_type(
718 em::DeviceRegisterResponse::ENTERPRISE);
719 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
720 Mock::VerifyAndClearExpectations(this);
721 EXPECT_TRUE(register_completed_);
722 EXPECT_EQ(dm_token_, expected_dm_token);
723 // UserCloudPolicyManager should not be initialized.
724 ASSERT_FALSE(manager_->core()->service());
727 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
728 // Initiate a policy fetch request.
729 MockDeviceManagementJob* fetch_request = NULL;
730 EXPECT_CALL(device_management_service_,
731 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
732 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
733 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
734 .Times(1);
735 UserPolicySigninService* signin_service =
736 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
737 signin_service->FetchPolicyForSignedInUser(
738 kTestUser,
739 "mock_dm_token",
740 "mock_client_id",
741 profile_->GetRequestContext(),
742 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
743 base::Unretained(this)));
744 ASSERT_TRUE(fetch_request);
746 // Make the policy fetch fail.
747 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
748 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
749 em::DeviceManagementResponse());
751 // UserCloudPolicyManager should be initialized.
752 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
753 ASSERT_TRUE(manager_->core()->service());
756 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
757 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
760 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
761 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
763 EXPECT_CALL(*mock_store_, Clear());
764 signin_manager_->ForceSignOut();
765 ASSERT_FALSE(manager_->core()->service());
767 // Now sign in again.
768 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
771 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
772 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
774 ASSERT_TRUE(manager_->IsClientRegistered());
776 // Kick off another policy fetch.
777 MockDeviceManagementJob* fetch_request = NULL;
778 EXPECT_CALL(device_management_service_,
779 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
780 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
781 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
782 .Times(1);
783 manager_->RefreshPolicies();
784 Mock::VerifyAndClearExpectations(this);
786 // Now, fake a transient error from the server on this policy fetch. This
787 // should have no impact on the cached policy.
788 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
789 em::DeviceManagementResponse());
790 base::RunLoop().RunUntilIdle();
791 ASSERT_TRUE(manager_->IsClientRegistered());
794 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
795 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
797 EXPECT_TRUE(manager_->IsClientRegistered());
798 #if !defined(OS_ANDROID)
799 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
800 #endif
802 // Kick off another policy fetch.
803 MockDeviceManagementJob* fetch_request = NULL;
804 EXPECT_CALL(device_management_service_,
805 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
806 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
807 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
808 .Times(1);
809 manager_->RefreshPolicies();
810 Mock::VerifyAndClearExpectations(this);
812 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
813 // indicates that chrome management is disabled and will result in the cached
814 // policy being removed and the manager shut down.
815 EXPECT_CALL(*mock_store_, Clear());
816 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
817 em::DeviceManagementResponse());
818 base::RunLoop().RunUntilIdle();
819 EXPECT_FALSE(manager_->IsClientRegistered());
820 #if !defined(OS_ANDROID)
821 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
822 #endif
825 } // namespace
827 } // namespace policy