Upstream version 5.34.92.0
[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/files/file_path.h"
6 #include "base/message_loop/message_loop.h"
7 #include "base/message_loop/message_loop_proxy.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/run_loop.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/fake_profile_oauth2_token_service.h"
18 #include "chrome/browser/signin/fake_signin_manager.h"
19 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
20 #include "chrome/browser/signin/signin_manager.h"
21 #include "chrome/browser/signin/signin_manager_factory.h"
22 #include "chrome/test/base/testing_browser_process.h"
23 #include "chrome/test/base/testing_pref_service_syncable.h"
24 #include "chrome/test/base/testing_profile.h"
25 #include "components/policy/core/browser/browser_policy_connector.h"
26 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
27 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
28 #include "components/policy/core/common/cloud/mock_device_management_service.h"
29 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
30 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
31 #include "components/policy/core/common/schema_registry.h"
32 #include "content/public/browser/browser_context.h"
33 #include "content/public/browser/notification_details.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_source.h"
36 #include "content/public/test/test_browser_thread_bundle.h"
37 #include "google_apis/gaia/gaia_constants.h"
38 #include "google_apis/gaia/google_service_auth_error.h"
39 #include "net/http/http_status_code.h"
40 #include "net/url_request/test_url_fetcher_factory.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "net/url_request/url_request_status.h"
43 #include "net/url_request/url_request_test_util.h"
44 #include "testing/gmock/include/gmock/gmock.h"
45 #include "testing/gtest/include/gtest/gtest.h"
46
47 #if defined(OS_ANDROID)
48 #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
49 #else
50 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
51 #endif
52
53 namespace em = enterprise_management;
54
55 using testing::AnyNumber;
56 using testing::Mock;
57 using testing::_;
58
59 namespace policy {
60
61 namespace {
62
63 const char kTestUser[] = "testuser@test.com";
64
65 #if !defined(OS_ANDROID)
66 const char kValidTokenResponse[] =
67     "{"
68     "  \"access_token\": \"at1\","
69     "  \"expires_in\": 3600,"
70     "  \"token_type\": \"Bearer\""
71     "}";
72 #endif
73
74 const char kHostedDomainResponse[] =
75     "{"
76     "  \"hd\": \"test.com\""
77     "}";
78
79 class SigninManagerFake : public FakeSigninManager {
80  public:
81   explicit SigninManagerFake(Profile* profile)
82       : FakeSigninManager(profile) {
83     Initialize(profile, NULL);
84   }
85
86   void ForceSignOut() {
87     // Allow signing out now.
88     prohibit_signout_ = false;
89     SignOut();
90   }
91
92   static BrowserContextKeyedService* Build(content::BrowserContext* profile) {
93     return new SigninManagerFake(static_cast<Profile*>(profile));
94   }
95 };
96
97 UserCloudPolicyManager* BuildCloudPolicyManager(
98     content::BrowserContext* context) {
99   MockUserCloudPolicyStore *store = new MockUserCloudPolicyStore();
100   EXPECT_CALL(*store, Load()).Times(AnyNumber());
101
102   return new UserCloudPolicyManager(
103       scoped_ptr<UserCloudPolicyStore>(store),
104       base::FilePath(),
105       scoped_ptr<CloudExternalDataManager>(),
106       base::MessageLoopProxy::current(),
107       base::MessageLoopProxy::current(),
108       base::MessageLoopProxy::current());
109 }
110
111 class UserPolicySigninServiceTest : public testing::Test {
112  public:
113   UserPolicySigninServiceTest()
114       : mock_store_(NULL),
115         thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
116         register_completed_(false) {}
117
118   MOCK_METHOD1(OnPolicyRefresh, void(bool));
119
120   void OnRegisterCompleted(const std::string& dm_token,
121                            const std::string& client_id) {
122     register_completed_ = true;
123     dm_token_ = dm_token;
124     client_id_ = client_id;
125   }
126
127   void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
128     // Policy client registration on Android depends on Token Service having
129     // a valid login token, while on other platforms, the login refresh token
130     // is specified directly.
131 #if defined(OS_ANDROID)
132     GetTokenService()->IssueRefreshTokenForUser(kTestUser,
133                                                 "oauth2_login_refresh_token");
134 #endif
135     service->RegisterForPolicy(
136         kTestUser,
137 #if !defined(OS_ANDROID)
138         "mock_oauth_token",
139 #endif
140         base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
141                    base::Unretained(this)));
142     ASSERT_TRUE(IsRequestActive());
143   }
144
145   virtual void SetUp() OVERRIDE {
146     UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
147         &device_management_service_);
148
149     local_state_.reset(new TestingPrefServiceSimple);
150     chrome::RegisterLocalState(local_state_->registry());
151     system_request_context_getter_ = new net::TestURLRequestContextGetter(
152         base::MessageLoopProxy::current());
153     TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
154         system_request_context_getter_.get());
155     TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
156
157     g_browser_process->browser_policy_connector()->Init(
158         local_state_.get(), system_request_context_getter_);
159
160     // Create a testing profile with cloud-policy-on-signin enabled, and bring
161     // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
162     scoped_ptr<TestingPrefServiceSyncable> prefs(
163         new TestingPrefServiceSyncable());
164     chrome::RegisterUserProfilePrefs(prefs->registry());
165
166     // UserCloudPolicyManagerFactory isn't a real
167     // BrowserContextKeyedServiceFactory (it derives from
168     // BrowserContextKeyedBaseFactory and exposes its own APIs to get
169     // instances) so we have to inject our testing factory via a special
170     // API before creating the profile.
171     UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
172         BuildCloudPolicyManager);
173     TestingProfile::Builder builder;
174     builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
175     builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
176                               SigninManagerFake::Build);
177     builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
178                               FakeProfileOAuth2TokenService::Build);
179
180     profile_ = builder.Build().Pass();
181     url_factory_.set_remove_fetcher_on_delete(true);
182
183     signin_manager_ = static_cast<SigninManagerFake*>(
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();
194
195     Mock::VerifyAndClearExpectations(mock_store_);
196   }
197
198   virtual 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->SetBrowserPolicyConnector(NULL);
208     base::RunLoop run_loop;
209     run_loop.RunUntilIdle();
210   }
211
212   virtual void AddProfile() {
213     // For this test, the user should not be signed in yet.
214     DCHECK(signin_manager_->GetAuthenticatedUsername().empty());
215
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());
219
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());
225   }
226
227   FakeProfileOAuth2TokenService* GetTokenService() {
228     ProfileOAuth2TokenService* service =
229         ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
230     return static_cast<FakeProfileOAuth2TokenService*>(service);
231   }
232
233   bool IsRequestActive() {
234     if (!GetTokenService()->GetPendingRequests().empty())
235       return true;
236     return url_factory_.GetFetcherByID(0);
237   }
238
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
250   }
251
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);
258   }
259
260   void TestSuccessfulSignin() {
261     UserPolicySigninService* signin_service =
262         UserPolicySigninServiceFactory::GetForProfile(profile_.get());
263     EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
264     RegisterPolicyClientWithCallback(signin_service);
265
266     // Mimic successful oauth token fetch.
267     MakeOAuthTokenFetchSucceed();
268
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);
278
279     // Now mimic the user being a hosted domain - this should cause a Register()
280     // call.
281     ReportHostedDomainStatus(true);
282
283     // Should have no more outstanding requests.
284     ASSERT_FALSE(IsRequestActive());
285     Mock::VerifyAndClearExpectations(this);
286     ASSERT_TRUE(register_request);
287
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);
297
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);
302
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);
310
311     signin_service->FetchPolicyForSignedInUser(
312         kTestUser,
313         dm_token_,
314         client_id_,
315         profile_->GetRequestContext(),
316         base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
317                    base::Unretained(this)));
318
319     Mock::VerifyAndClearExpectations(this);
320     ASSERT_TRUE(fetch_request);
321
322     // UserCloudPolicyManager should now be initialized.
323     EXPECT_EQ(mock_store_->signin_username_, kTestUser);
324     ASSERT_TRUE(manager_->core()->service());
325
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);
330
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);
340
341     // Complete the store which should cause the policy fetch callback to be
342     // invoked.
343     mock_store_->NotifyStoreLoaded();
344     Mock::VerifyAndClearExpectations(this);
345   }
346
347   scoped_ptr<TestingProfile> profile_;
348   MockUserCloudPolicyStore* mock_store_;  // Not owned.
349   SchemaRegistry schema_registry_;
350   scoped_ptr<UserCloudPolicyManager> manager_;
351
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_;
355
356   net::TestURLFetcherFactory url_factory_;
357
358   SigninManagerFake* signin_manager_;
359
360   // Used in conjunction with OnRegisterCompleted() to test client registration
361   // callbacks.
362   std::string dm_token_;
363   std::string client_id_;
364
365   // True if OnRegisterCompleted() was called.
366   bool register_completed_;
367
368   // Weak ptr to the MockDeviceManagementService (object is owned by the
369   // BrowserPolicyConnector).
370   MockDeviceManagementService device_management_service_;
371
372   scoped_ptr<TestingPrefServiceSimple> local_state_;
373   scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
374 };
375
376 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
377  public:
378   virtual void AddProfile() OVERRIDE {
379     // UserCloudPolicyManager should not be initialized.
380     ASSERT_FALSE(manager_->core()->service());
381
382     // Set the user as signed in.
383     SigninManagerFactory::GetForProfile(profile_.get())->
384         SetAuthenticatedUsername(kTestUser);
385
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());
391   }
392 };
393
394 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
395   // Make sure user is not signed in.
396   ASSERT_TRUE(SigninManagerFactory::GetForProfile(profile_.get())->
397       GetAuthenticatedUsername().empty());
398
399   // UserCloudPolicyManager should not be initialized.
400   ASSERT_FALSE(manager_->core()->service());
401 }
402
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)
407
408 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
409   // UserCloudPolicyManager should be initialized.
410   ASSERT_TRUE(manager_->core()->service());
411
412   // Complete initialization of the store.
413   mock_store_->NotifyStoreLoaded();
414
415   // No oauth access token yet, so client registration should be deferred.
416   ASSERT_FALSE(IsRequestActive());
417
418   // Make oauth token available.
419   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
420                                               "oauth_login_refresh_token");
421
422   // Client registration should be in progress since we now have an oauth token.
423   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
424   ASSERT_TRUE(IsRequestActive());
425 }
426
427 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
428   // UserCloudPolicyManager should be initialized.
429   ASSERT_TRUE(manager_->core()->service());
430
431   // Complete initialization of the store.
432   mock_store_->NotifyStoreLoaded();
433
434   // No oauth access token yet, so client registration should be deferred.
435   ASSERT_FALSE(IsRequestActive());
436
437   // Make oauth token available.
438   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
439                                               "oauth_login_refresh_token");
440
441   // Client registration should be in progress since we now have an oauth token.
442   ASSERT_TRUE(IsRequestActive());
443
444   // Now fail the access token fetch.
445   GoogleServiceAuthError error(
446       GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
447   GetTokenService()->IssueErrorForAllPendingRequests(error);
448   ASSERT_FALSE(IsRequestActive());
449 }
450
451 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
452   // UserCloudPolicyManager should not be initialized since there is no
453   // signed-in user.
454   ASSERT_FALSE(manager_->core()->service());
455
456   // Now sign in the user.
457   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
458       kTestUser);
459
460   // Complete initialization of the store.
461   mock_store_->NotifyStoreLoaded();
462
463   // Make oauth token available.
464   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
465                                               "oauth_login_refresh_token");
466
467   // UserCloudPolicyManager should be initialized.
468   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
469   ASSERT_TRUE(manager_->core()->service());
470
471   // Client registration should be in progress since we have an oauth token.
472   ASSERT_TRUE(IsRequestActive());
473 }
474
475 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
476   // UserCloudPolicyManager should not be initialized since there is no
477   // signed-in user.
478   ASSERT_FALSE(manager_->core()->service());
479
480   // Now sign in a non-enterprise user (blacklisted gmail.com domain).
481   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
482       "non_enterprise_user@gmail.com");
483
484   // Complete initialization of the store.
485   mock_store_->NotifyStoreLoaded();
486
487   // Make oauth token available.
488   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
489                                               "oauth_login_refresh_token");
490
491   // UserCloudPolicyManager should not be initialized and there should be no
492   // DMToken request active.
493   ASSERT_TRUE(!manager_->core()->service());
494   ASSERT_FALSE(IsRequestActive());
495 }
496
497 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
498   // UserCloudPolicyManager should not be initialized since there is no
499   // signed-in user.
500   ASSERT_FALSE(manager_->core()->service());
501
502   // Now sign in the user.
503   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
504       kTestUser);
505
506   // Make oauth token available.
507   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
508                                               "oauth_login_refresh_token");
509
510   // UserCloudPolicyManager should be initialized.
511   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
512   ASSERT_TRUE(manager_->core()->service());
513
514   // Client registration should not be in progress since the store is not
515   // yet initialized.
516   ASSERT_FALSE(IsRequestActive());
517
518   // Complete initialization of the store with no policy (unregistered client).
519   mock_store_->NotifyStoreLoaded();
520
521   // Client registration should be in progress since we have an oauth token.
522   ASSERT_TRUE(IsRequestActive());
523 }
524
525 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
526   // UserCloudPolicyManager should not be initialized since there is no
527   // signed-in user.
528   ASSERT_FALSE(manager_->core()->service());
529
530   // Now sign in the user.
531   SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
532       kTestUser);
533
534   // Make oauth token available.
535   GetTokenService()->IssueRefreshTokenForUser(kTestUser,
536                                               "oauth_login_refresh_token");
537
538   // UserCloudPolicyManager should be initialized.
539   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
540   ASSERT_TRUE(manager_->core()->service());
541
542   // Client registration should not be in progress since the store is not
543   // yet initialized.
544   ASSERT_FALSE(manager_->IsClientRegistered());
545   ASSERT_FALSE(IsRequestActive());
546
547   mock_store_->policy_.reset(new enterprise_management::PolicyData());
548   mock_store_->policy_->set_request_token("fake token");
549   mock_store_->policy_->set_device_id("fake client id");
550
551   // Complete initialization of the store.
552   mock_store_->NotifyStoreLoaded();
553
554   // Client registration should not be in progress since the client should be
555   // already registered.
556   ASSERT_TRUE(manager_->IsClientRegistered());
557   ASSERT_FALSE(IsRequestActive());
558 }
559
560 #endif  // !defined(OS_ANDROID)
561
562 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
563   // UserCloudPolicyManager should be initialized.
564   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
565   ASSERT_TRUE(manager_->core()->service());
566
567   // Signing out will clear the policy from the store.
568   EXPECT_CALL(*mock_store_, Clear());
569
570   // Now sign out.
571   SigninManagerFactory::GetForProfile(profile_.get())->SignOut();
572
573   // UserCloudPolicyManager should be shut down.
574   ASSERT_FALSE(manager_->core()->service());
575 }
576
577 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
578   UserPolicySigninService* signin_service =
579       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
580   RegisterPolicyClientWithCallback(signin_service);
581   Mock::VerifyAndClearExpectations(this);
582
583   // UserCloudPolicyManager should not be initialized.
584   ASSERT_FALSE(manager_->core()->service());
585   ASSERT_TRUE(IsRequestActive());
586   EXPECT_FALSE(register_completed_);
587
588   // Cause the access token fetch to fail - callback should be invoked.
589 #if defined(OS_ANDROID)
590   ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
591   GetTokenService()->IssueErrorForAllPendingRequests(
592       GoogleServiceAuthError::FromServiceError("fail"));
593 #else
594   net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
595   fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
596   fetcher->delegate()->OnURLFetchComplete(fetcher);
597 #endif
598
599   EXPECT_TRUE(register_completed_);
600   EXPECT_TRUE(dm_token_.empty());
601   EXPECT_FALSE(IsRequestActive());
602 }
603
604 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
605   UserPolicySigninService* signin_service =
606       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
607   RegisterPolicyClientWithCallback(signin_service);
608
609   // UserCloudPolicyManager should not be initialized.
610   ASSERT_FALSE(manager_->core()->service());
611   ASSERT_TRUE(IsRequestActive());
612
613   // Cause the access token request to succeed.
614   MakeOAuthTokenFetchSucceed();
615
616   // Should be a follow-up fetch to check the hosted-domain status.
617   ASSERT_TRUE(IsRequestActive());
618   Mock::VerifyAndClearExpectations(this);
619
620   EXPECT_FALSE(register_completed_);
621
622   // Report that the user is not on a hosted domain - callback should be
623   // invoked reporting a failed fetch.
624   ReportHostedDomainStatus(false);
625
626   // Since this is not a hosted domain, we should not issue a request for a
627   // DMToken.
628   EXPECT_TRUE(register_completed_);
629   EXPECT_TRUE(dm_token_.empty());
630   ASSERT_FALSE(IsRequestActive());
631 }
632
633 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
634   UserPolicySigninService* signin_service =
635       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
636   RegisterPolicyClientWithCallback(signin_service);
637
638   // UserCloudPolicyManager should not be initialized.
639   ASSERT_FALSE(manager_->core()->service());
640
641   // Mimic successful oauth token fetch.
642   MakeOAuthTokenFetchSucceed();
643
644   EXPECT_FALSE(register_completed_);
645
646   // When the user is from a hosted domain, this should kick off client
647   // registration.
648   MockDeviceManagementJob* register_request = NULL;
649   EXPECT_CALL(device_management_service_,
650               CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
651       .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
652   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
653         .Times(1);
654
655   // Now mimic the user being a hosted domain - this should cause a Register()
656   // call.
657   ReportHostedDomainStatus(true);
658
659   // Should have no more outstanding requests.
660   ASSERT_FALSE(IsRequestActive());
661   Mock::VerifyAndClearExpectations(this);
662   ASSERT_TRUE(register_request);
663   EXPECT_FALSE(register_completed_);
664
665   // Make client registration fail (hosted domain user that is not managed).
666   register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
667                                  em::DeviceManagementResponse());
668   EXPECT_TRUE(register_completed_);
669   EXPECT_TRUE(dm_token_.empty());
670 }
671
672 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
673   UserPolicySigninService* signin_service =
674       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
675   RegisterPolicyClientWithCallback(signin_service);
676
677   // Mimic successful oauth token fetch.
678   MakeOAuthTokenFetchSucceed();
679
680   // When the user is from a hosted domain, this should kick off client
681   // registration.
682   MockDeviceManagementJob* register_request = NULL;
683   EXPECT_CALL(device_management_service_,
684               CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
685       .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
686   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
687       .Times(1);
688
689   // Now mimic the user being a hosted domain - this should cause a Register()
690   // call.
691   ReportHostedDomainStatus(true);
692
693   // Should have no more outstanding requests.
694   ASSERT_FALSE(IsRequestActive());
695   Mock::VerifyAndClearExpectations(this);
696   ASSERT_TRUE(register_request);
697   EXPECT_FALSE(register_completed_);
698
699   em::DeviceManagementResponse registration_blob;
700   std::string expected_dm_token = "dm_token";
701   registration_blob.mutable_register_response()->set_device_management_token(
702       expected_dm_token);
703   registration_blob.mutable_register_response()->set_enrollment_type(
704       em::DeviceRegisterResponse::ENTERPRISE);
705   register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
706   Mock::VerifyAndClearExpectations(this);
707   EXPECT_TRUE(register_completed_);
708   EXPECT_EQ(dm_token_, expected_dm_token);
709   // UserCloudPolicyManager should not be initialized.
710   ASSERT_FALSE(manager_->core()->service());
711 }
712
713 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
714   // Initiate a policy fetch request.
715   MockDeviceManagementJob* fetch_request = NULL;
716   EXPECT_CALL(device_management_service_,
717               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
718       .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
719   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
720       .Times(1);
721   UserPolicySigninService* signin_service =
722       UserPolicySigninServiceFactory::GetForProfile(profile_.get());
723   signin_service->FetchPolicyForSignedInUser(
724       kTestUser,
725       "mock_dm_token",
726       "mock_client_id",
727       profile_->GetRequestContext(),
728       base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
729                  base::Unretained(this)));
730   ASSERT_TRUE(fetch_request);
731
732   // Make the policy fetch fail.
733   EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
734   fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
735                               em::DeviceManagementResponse());
736
737   // UserCloudPolicyManager should be initialized.
738   EXPECT_EQ(mock_store_->signin_username_, kTestUser);
739   ASSERT_TRUE(manager_->core()->service());
740 }
741
742 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
743   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
744 }
745
746 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
747   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
748
749   EXPECT_CALL(*mock_store_, Clear());
750   signin_manager_->ForceSignOut();
751   ASSERT_FALSE(manager_->core()->service());
752
753   // Now sign in again.
754   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
755 }
756
757 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
758   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
759
760   ASSERT_TRUE(manager_->IsClientRegistered());
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 transient error from the server on this policy fetch. This
773   // should have no impact on the cached policy.
774   fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
775                               em::DeviceManagementResponse());
776   base::RunLoop().RunUntilIdle();
777   ASSERT_TRUE(manager_->IsClientRegistered());
778 }
779
780 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
781   ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
782
783   EXPECT_TRUE(manager_->IsClientRegistered());
784 #if !defined(OS_ANDROID)
785   EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
786 #endif
787
788   // Kick off another policy fetch.
789   MockDeviceManagementJob* fetch_request = NULL;
790   EXPECT_CALL(device_management_service_,
791               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
792       .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
793   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
794       .Times(1);
795   manager_->RefreshPolicies();
796   Mock::VerifyAndClearExpectations(this);
797
798   // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
799   // indicates that chrome management is disabled and will result in the cached
800   // policy being removed and the manager shut down.
801   EXPECT_CALL(*mock_store_, Clear());
802   fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
803                               em::DeviceManagementResponse());
804   base::RunLoop().RunUntilIdle();
805   EXPECT_FALSE(manager_->IsClientRegistered());
806 #if !defined(OS_ANDROID)
807   EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
808 #endif
809 }
810
811 }  // namespace
812
813 }  // namespace policy