- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
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 "base/message_loop/message_loop.h"
6 #include "base/message_loop/message_loop_proxy.h"
7 #include "base/prefs/pref_service.h"
8 #include "base/run_loop.h"
9 #include "base/time/time.h"
10 #include "chrome/browser/browser_process.h"
11 #include "chrome/browser/chrome_notification_types.h"
12 #include "chrome/browser/policy/browser_policy_connector.h"
13 #include "chrome/browser/policy/cloud/cloud_external_data_manager.h"
14 #include "chrome/browser/policy/cloud/cloud_policy_constants.h"
15 #include "chrome/browser/policy/cloud/mock_device_management_service.h"
16 #include "chrome/browser/policy/cloud/mock_user_cloud_policy_store.h"
17 #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h"
18 #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
19 #include "chrome/browser/prefs/browser_prefs.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
22 #include "chrome/browser/signin/fake_signin_manager.h"
23 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
24 #include "chrome/browser/signin/signin_manager.h"
25 #include "chrome/browser/signin/signin_manager_factory.h"
26 #include "chrome/test/base/testing_browser_process.h"
27 #include "chrome/test/base/testing_pref_service_syncable.h"
28 #include "chrome/test/base/testing_profile.h"
29 #include "content/public/browser/browser_context.h"
30 #include "content/public/browser/notification_details.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/notification_source.h"
33 #include "content/public/test/test_browser_thread_bundle.h"
34 #include "google_apis/gaia/gaia_constants.h"
35 #include "google_apis/gaia/google_service_auth_error.h"
36 #include "net/http/http_status_code.h"
37 #include "net/url_request/test_url_fetcher_factory.h"
38 #include "net/url_request/url_request_context_getter.h"
39 #include "net/url_request/url_request_status.h"
40 #include "testing/gmock/include/gmock/gmock.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42
43 #if defined(OS_ANDROID)
44 #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
45 #else
46 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
47 #endif
48
49 namespace em = enterprise_management;
50
51 using testing::AnyNumber;
52 using testing::Mock;
53 using testing::_;
54
55 namespace policy {
56
57 namespace {
58
59 const char kTestUser[] = "testuser@test.com";
60
61 #if !defined(OS_ANDROID)
62 const char kValidTokenResponse[] =
63     "{"
64     "  \"access_token\": \"at1\","
65     "  \"expires_in\": 3600,"
66     "  \"token_type\": \"Bearer\""
67     "}";
68 #endif
69
70 const char kHostedDomainResponse[] =
71     "{"
72     "  \"hd\": \"test.com\""
73     "}";
74
75 class SigninManagerFake : public FakeSigninManager {
76  public:
77   explicit SigninManagerFake(Profile* profile)
78       : FakeSigninManager(profile) {
79     Initialize(profile, NULL);
80   }
81
82   void ForceSignOut() {
83     // Allow signing out now.
84     prohibit_signout_ = false;
85     SignOut();
86   }
87
88   static BrowserContextKeyedService* Build(content::BrowserContext* profile) {
89     return new SigninManagerFake(static_cast<Profile*>(profile));
90   }
91 };
92
93 class UserPolicySigninServiceTest : public testing::Test {
94  public:
95   UserPolicySigninServiceTest()
96       : mock_store_(NULL),
97         thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
98         register_completed_(false) {}
99
100   MOCK_METHOD1(OnPolicyRefresh, void(bool));
101
102   void OnRegisterCompleted(scoped_ptr<CloudPolicyClient> client) {
103     register_completed_ = true;
104     created_client_.swap(client);
105   }
106
107   void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
108     // Policy client registration on Android depends on Token Service having
109     // a valid login token, while on other platforms, the login refresh token
110     // is specified directly.
111 #if defined(OS_ANDROID)
112     GetTokenService()->IssueRefreshToken("oauth2_login_refresh_token");
113 #endif
114     service->RegisterPolicyClient(
115         kTestUser,
116 #if !defined(OS_ANDROID)
117         "mock_oauth_token",
118 #endif
119         base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
120                    base::Unretained(this)));
121     ASSERT_TRUE(IsRequestActive());
122   }
123
124   virtual void SetUp() OVERRIDE {
125     UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
126         &device_management_service_);
127
128     local_state_.reset(new TestingPrefServiceSimple);
129     chrome::RegisterLocalState(local_state_->registry());
130     TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
131
132     scoped_refptr<net::URLRequestContextGetter> system_request_context;
133     g_browser_process->browser_policy_connector()->Init(
134         local_state_.get(), system_request_context);
135
136     // Create a testing profile with cloud-policy-on-signin enabled, and bring
137     // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
138     scoped_ptr<TestingPrefServiceSyncable> prefs(
139         new TestingPrefServiceSyncable());
140     chrome::RegisterUserProfilePrefs(prefs->registry());
141     TestingProfile::Builder builder;
142     builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
143     builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
144                               SigninManagerFake::Build);
145     builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
146                               FakeProfileOAuth2TokenService::Build);
147
148     profile_ = builder.Build().Pass();
149     signin_manager_ = static_cast<SigninManagerFake*>(
150         SigninManagerFactory::GetForProfile(profile_.get()));
151
152     mock_store_ = new MockUserCloudPolicyStore();
153     EXPECT_CALL(*mock_store_, Load()).Times(AnyNumber());
154     manager_.reset(new UserCloudPolicyManager(
155         profile_.get(),
156         scoped_ptr<UserCloudPolicyStore>(mock_store_),
157         scoped_ptr<CloudExternalDataManager>(),
158         base::MessageLoopProxy::current()));
159
160     Mock::VerifyAndClearExpectations(mock_store_);
161     url_factory_.set_remove_fetcher_on_delete(true);
162   }
163
164   virtual void TearDown() OVERRIDE {
165     UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
166     // Free the profile before we clear out the browser prefs.
167     profile_.reset();
168     TestingBrowserProcess* testing_browser_process =
169         TestingBrowserProcess::GetGlobal();
170     testing_browser_process->SetLocalState(NULL);
171     local_state_.reset();
172     testing_browser_process->SetBrowserPolicyConnector(NULL);
173     base::RunLoop run_loop;
174     run_loop.RunUntilIdle();
175   }
176
177   FakeProfileOAuth2TokenService* GetTokenService() {
178     ProfileOAuth2TokenService* service =
179         ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
180     return static_cast<FakeProfileOAuth2TokenService*>(service);
181   }
182
183   bool IsRequestActive() {
184     if (!GetTokenService()->GetPendingRequests().empty())
185       return true;
186     return url_factory_.GetFetcherByID(0);
187   }
188
189   void MakeOAuthTokenFetchSucceed() {
190     ASSERT_TRUE(IsRequestActive());
191 #if defined(OS_ANDROID)
192     GetTokenService()->IssueTokenForAllPendingRequests("access_token",
193                                                        base::Time::Now());
194 #else
195     net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
196     fetcher->set_response_code(net::HTTP_OK);
197     fetcher->SetResponseString(kValidTokenResponse);
198     fetcher->delegate()->OnURLFetchComplete(fetcher);
199 #endif
200   }
201
202   void ReportHostedDomainStatus(bool is_hosted_domain) {
203     ASSERT_TRUE(IsRequestActive());
204     net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
205     fetcher->set_response_code(net::HTTP_OK);
206     fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
207     fetcher->delegate()->OnURLFetchComplete(fetcher);
208   }
209
210   void TestSuccessfulSignin() {
211     UserPolicySigninService* signin_service =
212         UserPolicySigninServiceFactory::GetForProfile(profile_.get());
213     EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
214     RegisterPolicyClientWithCallback(signin_service);
215
216     // Mimic successful oauth token fetch.
217     MakeOAuthTokenFetchSucceed();
218
219     // When the user is from a hosted domain, this should kick off client
220     // registration.
221     MockDeviceManagementJob* register_request = NULL;
222     EXPECT_CALL(device_management_service_,
223                 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
224         .WillOnce(device_management_service_.CreateAsyncJob(
225             &register_request));
226     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
227         .Times(1);
228
229     // Now mimic the user being a hosted domain - this should cause a Register()
230     // call.
231     ReportHostedDomainStatus(true);
232
233     // Should have no more outstanding requests.
234     ASSERT_FALSE(IsRequestActive());
235     Mock::VerifyAndClearExpectations(this);
236     ASSERT_TRUE(register_request);
237
238     // Mimic successful client registration - this should register the client
239     // and invoke the callback.
240     em::DeviceManagementResponse registration_blob;
241     registration_blob.mutable_register_response()->set_device_management_token(
242         "dm_token");
243     registration_blob.mutable_register_response()->set_enrollment_type(
244         em::DeviceRegisterResponse::ENTERPRISE);
245     register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
246
247     // UserCloudPolicyManager should not be initialized yet.
248     ASSERT_FALSE(manager_->core()->service());
249     EXPECT_TRUE(register_completed_);
250     EXPECT_TRUE(created_client_.get());
251
252     // Now call to fetch policy - this should fire off a fetch request.
253     MockDeviceManagementJob* fetch_request = NULL;
254     EXPECT_CALL(device_management_service_,
255                 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
256         .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
257     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
258         .Times(1);
259     signin_service->FetchPolicyForSignedInUser(
260         created_client_.Pass(),
261         base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
262                    base::Unretained(this)));
263
264     Mock::VerifyAndClearExpectations(this);
265     ASSERT_TRUE(fetch_request);
266
267     // UserCloudPolicyManager should now be initialized.
268     ASSERT_TRUE(manager_->core()->service());
269
270     // Make the policy fetch succeed - this should result in a write to the
271     // store and ultimately result in a call to OnPolicyRefresh().
272     EXPECT_CALL(*mock_store_, Store(_));
273     EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
274
275     // Create a fake policy blob to deliver to the client.
276     em::DeviceManagementResponse policy_blob;
277     em::PolicyData policy_data;
278     policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
279     em::PolicyFetchResponse* policy_response =
280         policy_blob.mutable_policy_response()->add_response();
281     ASSERT_TRUE(policy_data.SerializeToString(
282         policy_response->mutable_policy_data()));
283     fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
284
285     // Complete the store which should cause the policy fetch callback to be
286     // invoked.
287     mock_store_->NotifyStoreLoaded();
288     Mock::VerifyAndClearExpectations(this);
289   }
290
291   scoped_ptr<TestingProfile> profile_;
292   MockUserCloudPolicyStore* mock_store_;  // Not owned.
293   scoped_ptr<UserCloudPolicyManager> manager_;
294
295   // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
296   // various components asynchronously via tasks, so create fake threads here.
297   content::TestBrowserThreadBundle thread_bundle_;
298
299   net::TestURLFetcherFactory url_factory_;
300
301   SigninManagerFake* signin_manager_;
302
303   // Used in conjunction with OnRegisterCompleted() to test client registration
304   // callbacks.
305   scoped_ptr<CloudPolicyClient> created_client_;
306
307   // True if OnRegisterCompleted() was called.
308   bool register_completed_;
309
310   // Weak ptr to the MockDeviceManagementService (object is owned by the
311   // BrowserPolicyConnector).
312   MockDeviceManagementService device_management_service_;
313
314   scoped_ptr<TestingPrefServiceSimple> local_state_;
315 };
316
317 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
318   EXPECT_CALL(*mock_store_, Clear());
319   // Make sure user is not signed in.
320   ASSERT_TRUE(SigninManagerFactory::GetForProfile(profile_.get())->
321       GetAuthenticatedUsername().empty());
322
323   // Let the SigninService know that the profile has been created.
324   content::NotificationService::current()->Notify(
325       chrome::NOTIFICATION_PROFILE_ADDED,
326       content::Source<Profile>(profile_.get()),
327       content::NotificationService::NoDetails());
328
329   // UserCloudPolicyManager should not be initialized.
330   ASSERT_FALSE(manager_->core()->service());
331 }
332
333   // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
334   // token after signin. Revisit this after figuring how to handle that on
335   // Android.
336 #if !defined(OS_ANDROID)
337
338 TEST_F(UserPolicySigninServiceTest, InitWhileSignedIn) {
339   // Set the user as signed in.
340   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
341       kTestUser);
342
343   // Let the SigninService know that the profile has been created.
344   content::NotificationService::current()->Notify(
345       chrome::NOTIFICATION_PROFILE_ADDED,
346       content::Source<Profile>(profile_.get()),
347       content::NotificationService::NoDetails());
348
349   // UserCloudPolicyManager should be initialized.
350   ASSERT_TRUE(manager_->core()->service());
351
352   // Complete initialization of the store.
353   mock_store_->NotifyStoreLoaded();
354
355   // No oauth access token yet, so client registration should be deferred.
356   ASSERT_FALSE(IsRequestActive());
357
358   // Make oauth token available.
359   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
360
361   // Client registration should be in progress since we now have an oauth token.
362   ASSERT_TRUE(IsRequestActive());
363 }
364
365 TEST_F(UserPolicySigninServiceTest, InitWhileSignedInOAuthError) {
366   // Set the user as signed in.
367   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
368       kTestUser);
369
370   // Let the SigninService know that the profile has been created.
371   content::NotificationService::current()->Notify(
372       chrome::NOTIFICATION_PROFILE_ADDED,
373       content::Source<Profile>(profile_.get()),
374       content::NotificationService::NoDetails());
375
376   // UserCloudPolicyManager should be initialized.
377   ASSERT_TRUE(manager_->core()->service());
378
379   // Complete initialization of the store.
380   mock_store_->NotifyStoreLoaded();
381
382   // No oauth access token yet, so client registration should be deferred.
383   ASSERT_FALSE(IsRequestActive());
384
385   // Make oauth token available.
386   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
387
388   // Client registration should be in progress since we now have an oauth token.
389   ASSERT_TRUE(IsRequestActive());
390
391   // Now fail the access token fetch.
392   GoogleServiceAuthError error(
393       GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
394   GetTokenService()->IssueErrorForAllPendingRequests(error);
395   ASSERT_FALSE(IsRequestActive());
396 }
397
398 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
399   EXPECT_CALL(*mock_store_, Clear());
400   // Let the SigninService know that the profile has been created.
401   content::NotificationService::current()->Notify(
402       chrome::NOTIFICATION_PROFILE_ADDED,
403       content::Source<Profile>(profile_.get()),
404       content::NotificationService::NoDetails());
405
406   // UserCloudPolicyManager should not be initialized since there is no
407   // signed-in user.
408   ASSERT_FALSE(manager_->core()->service());
409
410   // Now sign in the user.
411   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
412       kTestUser);
413
414   // Complete initialization of the store.
415   mock_store_->NotifyStoreLoaded();
416
417   // Make oauth token available.
418   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
419
420   // UserCloudPolicyManager should be initialized.
421   ASSERT_TRUE(manager_->core()->service());
422
423   // Client registration should be in progress since we have an oauth token.
424   ASSERT_TRUE(IsRequestActive());
425 }
426
427 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
428   EXPECT_CALL(*mock_store_, Clear());
429   // Let the SigninService know that the profile has been created.
430   content::NotificationService::current()->Notify(
431       chrome::NOTIFICATION_PROFILE_ADDED,
432       content::Source<Profile>(profile_.get()),
433       content::NotificationService::NoDetails());
434
435   // UserCloudPolicyManager should not be initialized since there is no
436   // signed-in user.
437   ASSERT_FALSE(manager_->core()->service());
438
439   // Now sign in a non-enterprise user (blacklisted gmail.com domain).
440   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
441       "non_enterprise_user@gmail.com");
442
443   // Complete initialization of the store.
444   mock_store_->NotifyStoreLoaded();
445
446   // Make oauth token available.
447   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
448
449   // UserCloudPolicyManager should not be initialized and there should be no
450   // DMToken request active.
451   ASSERT_TRUE(!manager_->core()->service());
452   ASSERT_FALSE(IsRequestActive());
453 }
454
455 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
456   EXPECT_CALL(*mock_store_, Clear());
457   // Let the SigninService know that the profile has been created.
458   content::NotificationService::current()->Notify(
459       chrome::NOTIFICATION_PROFILE_ADDED,
460       content::Source<Profile>(profile_.get()),
461       content::NotificationService::NoDetails());
462
463   // UserCloudPolicyManager should not be initialized since there is no
464   // signed-in user.
465   ASSERT_FALSE(manager_->core()->service());
466
467   // Now sign in the user.
468   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
469       kTestUser);
470
471   // Make oauth token available.
472   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
473
474   // UserCloudPolicyManager should be initialized.
475   ASSERT_TRUE(manager_->core()->service());
476
477   // Client registration should not be in progress since the store is not
478   // yet initialized.
479   ASSERT_FALSE(IsRequestActive());
480
481   // Complete initialization of the store with no policy (unregistered client).
482   mock_store_->NotifyStoreLoaded();
483
484   // Client registration should be in progress since we have an oauth token.
485   ASSERT_TRUE(IsRequestActive());
486 }
487
488 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
489   EXPECT_CALL(*mock_store_, Clear());
490   // Let the SigninService know that the profile has been created.
491   content::NotificationService::current()->Notify(
492       chrome::NOTIFICATION_PROFILE_ADDED,
493       content::Source<Profile>(profile_.get()),
494       content::NotificationService::NoDetails());
495
496   // UserCloudPolicyManager should not be initialized since there is no
497   // signed-in user.
498   ASSERT_FALSE(manager_->core()->service());
499
500   // Now sign in the user.
501   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
502       kTestUser);
503
504   // Make oauth token available.
505   GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
506
507   // UserCloudPolicyManager should be initialized.
508   ASSERT_TRUE(manager_->core()->service());
509
510   // Client registration should not be in progress since the store is not
511   // yet initialized.
512   ASSERT_FALSE(manager_->IsClientRegistered());
513   ASSERT_FALSE(IsRequestActive());
514
515   mock_store_->policy_.reset(new enterprise_management::PolicyData());
516   mock_store_->policy_->set_request_token("fake token");
517   mock_store_->policy_->set_device_id("fake client id");
518
519   // Complete initialization of the store.
520   mock_store_->NotifyStoreLoaded();
521
522   // Client registration should not be in progress since the client should be
523   // already registered.
524   ASSERT_TRUE(manager_->IsClientRegistered());
525   ASSERT_FALSE(IsRequestActive());
526 }
527
528 #endif  // !defined(OS_ANDROID)
529
530 TEST_F(UserPolicySigninServiceTest, SignOutAfterInit) {
531   EXPECT_CALL(*mock_store_, Clear());
532   // Set the user as signed in.
533   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
534       kTestUser);
535
536   // Let the SigninService know that the profile has been created.
537   content::NotificationService::current()->Notify(
538       chrome::NOTIFICATION_PROFILE_ADDED,
539       content::Source<Profile>(profile_.get()),
540       content::NotificationService::NoDetails());
541
542   // UserCloudPolicyManager should be initialized.
543   ASSERT_TRUE(manager_->core()->service());
544
545   // Now sign out.
546   SigninManagerFactory::GetForProfile(profile_.get())->SignOut();
547
548   // UserCloudPolicyManager should be shut down.
549   ASSERT_FALSE(manager_->core()->service());
550 }
551
552 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
553   UserPolicySigninService* signin_service =
554       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
555   RegisterPolicyClientWithCallback(signin_service);
556   Mock::VerifyAndClearExpectations(this);
557
558   // UserCloudPolicyManager should not be initialized.
559   ASSERT_FALSE(manager_->core()->service());
560   ASSERT_TRUE(IsRequestActive());
561   EXPECT_FALSE(register_completed_);
562
563   // Cause the access token fetch to fail - callback should be invoked.
564 #if defined(OS_ANDROID)
565   ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
566   GetTokenService()->IssueErrorForAllPendingRequests(
567       GoogleServiceAuthError::FromServiceError("fail"));
568 #else
569   net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
570   fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
571   fetcher->delegate()->OnURLFetchComplete(fetcher);
572 #endif
573
574   EXPECT_TRUE(register_completed_);
575   EXPECT_FALSE(created_client_.get());
576   EXPECT_FALSE(IsRequestActive());
577 }
578
579 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
580   UserPolicySigninService* signin_service =
581       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
582   RegisterPolicyClientWithCallback(signin_service);
583
584   // UserCloudPolicyManager should not be initialized.
585   ASSERT_FALSE(manager_->core()->service());
586   ASSERT_TRUE(IsRequestActive());
587
588   // Cause the access token request to succeed.
589   MakeOAuthTokenFetchSucceed();
590
591   // Should be a follow-up fetch to check the hosted-domain status.
592   ASSERT_TRUE(IsRequestActive());
593   Mock::VerifyAndClearExpectations(this);
594
595   EXPECT_FALSE(register_completed_);
596
597   // Report that the user is not on a hosted domain - callback should be
598   // invoked reporting a failed fetch.
599   ReportHostedDomainStatus(false);
600
601   // Since this is not a hosted domain, we should not issue a request for a
602   // DMToken.
603   EXPECT_TRUE(register_completed_);
604   EXPECT_FALSE(created_client_.get());
605   ASSERT_FALSE(IsRequestActive());
606 }
607
608 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
609   UserPolicySigninService* signin_service =
610       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
611   RegisterPolicyClientWithCallback(signin_service);
612
613   // UserCloudPolicyManager should not be initialized.
614   ASSERT_FALSE(manager_->core()->service());
615
616   // Mimic successful oauth token fetch.
617   MakeOAuthTokenFetchSucceed();
618
619   EXPECT_FALSE(register_completed_);
620
621   // When the user is from a hosted domain, this should kick off client
622   // registration.
623   MockDeviceManagementJob* register_request = NULL;
624   EXPECT_CALL(device_management_service_,
625               CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
626       .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
627   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
628         .Times(1);
629
630   // Now mimic the user being a hosted domain - this should cause a Register()
631   // call.
632   ReportHostedDomainStatus(true);
633
634   // Should have no more outstanding requests.
635   ASSERT_FALSE(IsRequestActive());
636   Mock::VerifyAndClearExpectations(this);
637   ASSERT_TRUE(register_request);
638   EXPECT_FALSE(register_completed_);
639
640   // Make client registration fail (hosted domain user that is not managed).
641   register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
642                                  em::DeviceManagementResponse());
643   EXPECT_TRUE(register_completed_);
644   EXPECT_FALSE(created_client_.get());
645 }
646
647 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
648   UserPolicySigninService* signin_service =
649       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
650   RegisterPolicyClientWithCallback(signin_service);
651
652   // Mimic successful oauth token fetch.
653   MakeOAuthTokenFetchSucceed();
654
655   // When the user is from a hosted domain, this should kick off client
656   // registration.
657   MockDeviceManagementJob* register_request = NULL;
658   EXPECT_CALL(device_management_service_,
659               CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
660       .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
661   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
662       .Times(1);
663
664   // Now mimic the user being a hosted domain - this should cause a Register()
665   // call.
666   ReportHostedDomainStatus(true);
667
668   // Should have no more outstanding requests.
669   ASSERT_FALSE(IsRequestActive());
670   Mock::VerifyAndClearExpectations(this);
671   ASSERT_TRUE(register_request);
672   EXPECT_FALSE(register_completed_);
673
674   em::DeviceManagementResponse registration_blob;
675   registration_blob.mutable_register_response()->set_device_management_token(
676       "dm_token");
677   registration_blob.mutable_register_response()->set_enrollment_type(
678       em::DeviceRegisterResponse::ENTERPRISE);
679   register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
680   Mock::VerifyAndClearExpectations(this);
681   EXPECT_TRUE(register_completed_);
682   EXPECT_TRUE(created_client_.get());
683   // UserCloudPolicyManager should not be initialized.
684   ASSERT_FALSE(manager_->core()->service());
685 }
686
687 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
688   scoped_ptr<CloudPolicyClient> client =
689       UserCloudPolicyManager::CreateCloudPolicyClient(
690           &device_management_service_);
691   client->SetupRegistration("mock_dm_token", "mock_client_id");
692
693   // Initiate a policy fetch request.
694   MockDeviceManagementJob* fetch_request = NULL;
695   EXPECT_CALL(device_management_service_,
696               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
697       .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
698   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
699       .Times(1);
700   UserPolicySigninService* signin_service =
701       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
702   signin_service->FetchPolicyForSignedInUser(
703       client.Pass(),
704       base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
705                  base::Unretained(this)));
706   ASSERT_TRUE(fetch_request);
707
708   // Make the policy fetch fail.
709   EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
710   fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
711                               em::DeviceManagementResponse());
712   // UserCloudPolicyManager should be initialized.
713   ASSERT_TRUE(manager_->core()->service());
714 }
715
716 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
717   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
718 }
719
720 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
721   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
722
723   EXPECT_CALL(*mock_store_, Clear());
724   signin_manager_->ForceSignOut();
725   ASSERT_FALSE(manager_->core()->service());
726
727   // Now sign in again.
728   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
729 }
730
731 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
732   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
733
734   ASSERT_TRUE(manager_->IsClientRegistered());
735
736   // Kick off another policy fetch.
737   MockDeviceManagementJob* fetch_request = NULL;
738   EXPECT_CALL(device_management_service_,
739               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
740       .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
741   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
742       .Times(1);
743   manager_->RefreshPolicies();
744   Mock::VerifyAndClearExpectations(this);
745
746   // Now, fake a transient error from the server on this policy fetch. This
747   // should have no impact on the cached policy.
748   fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
749                               em::DeviceManagementResponse());
750   base::RunLoop().RunUntilIdle();
751   ASSERT_TRUE(manager_->IsClientRegistered());
752 }
753
754 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
755   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
756
757   EXPECT_TRUE(manager_->IsClientRegistered());
758 #if !defined(OS_ANDROID)
759   EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
760 #endif
761
762   // Kick off another policy fetch.
763   MockDeviceManagementJob* fetch_request = NULL;
764   EXPECT_CALL(device_management_service_,
765               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
766       .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
767   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
768       .Times(1);
769   manager_->RefreshPolicies();
770   Mock::VerifyAndClearExpectations(this);
771
772   // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
773   // indicates that chrome management is disabled and will result in the cached
774   // policy being removed and the manager shut down.
775   EXPECT_CALL(*mock_store_, Clear());
776   fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
777                               em::DeviceManagementResponse());
778   base::RunLoop().RunUntilIdle();
779   EXPECT_FALSE(manager_->IsClientRegistered());
780 #if !defined(OS_ANDROID)
781   EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
782 #endif
783 }
784
785 }  // namespace
786
787 }  // namespace policy