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