1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/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"
43 #if defined(OS_ANDROID)
44 #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
46 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
49 namespace em = enterprise_management;
51 using testing::AnyNumber;
59 const char kTestUser[] = "testuser@test.com";
61 #if !defined(OS_ANDROID)
62 const char kValidTokenResponse[] =
64 " \"access_token\": \"at1\","
65 " \"expires_in\": 3600,"
66 " \"token_type\": \"Bearer\""
70 const char kHostedDomainResponse[] =
72 " \"hd\": \"test.com\""
75 class SigninManagerFake : public FakeSigninManager {
77 explicit SigninManagerFake(Profile* profile)
78 : FakeSigninManager(profile) {
79 Initialize(profile, NULL);
83 // Allow signing out now.
84 prohibit_signout_ = false;
88 static BrowserContextKeyedService* Build(content::BrowserContext* profile) {
89 return new SigninManagerFake(static_cast<Profile*>(profile));
93 class UserPolicySigninServiceTest : public testing::Test {
95 UserPolicySigninServiceTest()
97 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
98 register_completed_(false) {}
100 MOCK_METHOD1(OnPolicyRefresh, void(bool));
102 void OnRegisterCompleted(scoped_ptr<CloudPolicyClient> client) {
103 register_completed_ = true;
104 created_client_.swap(client);
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");
114 service->RegisterPolicyClient(
116 #if !defined(OS_ANDROID)
119 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
120 base::Unretained(this)));
121 ASSERT_TRUE(IsRequestActive());
124 virtual void SetUp() OVERRIDE {
125 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
126 &device_management_service_);
128 local_state_.reset(new TestingPrefServiceSimple);
129 chrome::RegisterLocalState(local_state_->registry());
130 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
132 scoped_refptr<net::URLRequestContextGetter> system_request_context;
133 g_browser_process->browser_policy_connector()->Init(
134 local_state_.get(), system_request_context);
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);
148 profile_ = builder.Build().Pass();
149 signin_manager_ = static_cast<SigninManagerFake*>(
150 SigninManagerFactory::GetForProfile(profile_.get()));
152 mock_store_ = new MockUserCloudPolicyStore();
153 EXPECT_CALL(*mock_store_, Load()).Times(AnyNumber());
154 manager_.reset(new UserCloudPolicyManager(
156 scoped_ptr<UserCloudPolicyStore>(mock_store_),
157 scoped_ptr<CloudExternalDataManager>(),
158 base::MessageLoopProxy::current()));
160 Mock::VerifyAndClearExpectations(mock_store_);
161 url_factory_.set_remove_fetcher_on_delete(true);
164 virtual void TearDown() OVERRIDE {
165 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
166 // Free the profile before we clear out the browser prefs.
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();
177 FakeProfileOAuth2TokenService* GetTokenService() {
178 ProfileOAuth2TokenService* service =
179 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
180 return static_cast<FakeProfileOAuth2TokenService*>(service);
183 bool IsRequestActive() {
184 if (!GetTokenService()->GetPendingRequests().empty())
186 return url_factory_.GetFetcherByID(0);
189 void MakeOAuthTokenFetchSucceed() {
190 ASSERT_TRUE(IsRequestActive());
191 #if defined(OS_ANDROID)
192 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
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);
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);
210 void TestSuccessfulSignin() {
211 UserPolicySigninService* signin_service =
212 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
213 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
214 RegisterPolicyClientWithCallback(signin_service);
216 // Mimic successful oauth token fetch.
217 MakeOAuthTokenFetchSucceed();
219 // When the user is from a hosted domain, this should kick off client
221 MockDeviceManagementJob* register_request = NULL;
222 EXPECT_CALL(device_management_service_,
223 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
224 .WillOnce(device_management_service_.CreateAsyncJob(
226 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
229 // Now mimic the user being a hosted domain - this should cause a Register()
231 ReportHostedDomainStatus(true);
233 // Should have no more outstanding requests.
234 ASSERT_FALSE(IsRequestActive());
235 Mock::VerifyAndClearExpectations(this);
236 ASSERT_TRUE(register_request);
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(
243 registration_blob.mutable_register_response()->set_enrollment_type(
244 em::DeviceRegisterResponse::ENTERPRISE);
245 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
247 // UserCloudPolicyManager should not be initialized yet.
248 ASSERT_FALSE(manager_->core()->service());
249 EXPECT_TRUE(register_completed_);
250 EXPECT_TRUE(created_client_.get());
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(_, _, _, _, _, _, _))
259 signin_service->FetchPolicyForSignedInUser(
260 created_client_.Pass(),
261 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
262 base::Unretained(this)));
264 Mock::VerifyAndClearExpectations(this);
265 ASSERT_TRUE(fetch_request);
267 // UserCloudPolicyManager should now be initialized.
268 ASSERT_TRUE(manager_->core()->service());
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);
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);
285 // Complete the store which should cause the policy fetch callback to be
287 mock_store_->NotifyStoreLoaded();
288 Mock::VerifyAndClearExpectations(this);
291 scoped_ptr<TestingProfile> profile_;
292 MockUserCloudPolicyStore* mock_store_; // Not owned.
293 scoped_ptr<UserCloudPolicyManager> manager_;
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_;
299 net::TestURLFetcherFactory url_factory_;
301 SigninManagerFake* signin_manager_;
303 // Used in conjunction with OnRegisterCompleted() to test client registration
305 scoped_ptr<CloudPolicyClient> created_client_;
307 // True if OnRegisterCompleted() was called.
308 bool register_completed_;
310 // Weak ptr to the MockDeviceManagementService (object is owned by the
311 // BrowserPolicyConnector).
312 MockDeviceManagementService device_management_service_;
314 scoped_ptr<TestingPrefServiceSimple> local_state_;
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());
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());
329 // UserCloudPolicyManager should not be initialized.
330 ASSERT_FALSE(manager_->core()->service());
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
336 #if !defined(OS_ANDROID)
338 TEST_F(UserPolicySigninServiceTest, InitWhileSignedIn) {
339 // Set the user as signed in.
340 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
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());
349 // UserCloudPolicyManager should be initialized.
350 ASSERT_TRUE(manager_->core()->service());
352 // Complete initialization of the store.
353 mock_store_->NotifyStoreLoaded();
355 // No oauth access token yet, so client registration should be deferred.
356 ASSERT_FALSE(IsRequestActive());
358 // Make oauth token available.
359 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
361 // Client registration should be in progress since we now have an oauth token.
362 ASSERT_TRUE(IsRequestActive());
365 TEST_F(UserPolicySigninServiceTest, InitWhileSignedInOAuthError) {
366 // Set the user as signed in.
367 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
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());
376 // UserCloudPolicyManager should be initialized.
377 ASSERT_TRUE(manager_->core()->service());
379 // Complete initialization of the store.
380 mock_store_->NotifyStoreLoaded();
382 // No oauth access token yet, so client registration should be deferred.
383 ASSERT_FALSE(IsRequestActive());
385 // Make oauth token available.
386 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
388 // Client registration should be in progress since we now have an oauth token.
389 ASSERT_TRUE(IsRequestActive());
391 // Now fail the access token fetch.
392 GoogleServiceAuthError error(
393 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
394 GetTokenService()->IssueErrorForAllPendingRequests(error);
395 ASSERT_FALSE(IsRequestActive());
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());
406 // UserCloudPolicyManager should not be initialized since there is no
408 ASSERT_FALSE(manager_->core()->service());
410 // Now sign in the user.
411 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
414 // Complete initialization of the store.
415 mock_store_->NotifyStoreLoaded();
417 // Make oauth token available.
418 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
420 // UserCloudPolicyManager should be initialized.
421 ASSERT_TRUE(manager_->core()->service());
423 // Client registration should be in progress since we have an oauth token.
424 ASSERT_TRUE(IsRequestActive());
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());
435 // UserCloudPolicyManager should not be initialized since there is no
437 ASSERT_FALSE(manager_->core()->service());
439 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
440 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
441 "non_enterprise_user@gmail.com");
443 // Complete initialization of the store.
444 mock_store_->NotifyStoreLoaded();
446 // Make oauth token available.
447 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
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());
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());
463 // UserCloudPolicyManager should not be initialized since there is no
465 ASSERT_FALSE(manager_->core()->service());
467 // Now sign in the user.
468 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
471 // Make oauth token available.
472 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
474 // UserCloudPolicyManager should be initialized.
475 ASSERT_TRUE(manager_->core()->service());
477 // Client registration should not be in progress since the store is not
479 ASSERT_FALSE(IsRequestActive());
481 // Complete initialization of the store with no policy (unregistered client).
482 mock_store_->NotifyStoreLoaded();
484 // Client registration should be in progress since we have an oauth token.
485 ASSERT_TRUE(IsRequestActive());
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());
496 // UserCloudPolicyManager should not be initialized since there is no
498 ASSERT_FALSE(manager_->core()->service());
500 // Now sign in the user.
501 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
504 // Make oauth token available.
505 GetTokenService()->IssueRefreshToken("oauth_login_refresh_token");
507 // UserCloudPolicyManager should be initialized.
508 ASSERT_TRUE(manager_->core()->service());
510 // Client registration should not be in progress since the store is not
512 ASSERT_FALSE(manager_->IsClientRegistered());
513 ASSERT_FALSE(IsRequestActive());
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");
519 // Complete initialization of the store.
520 mock_store_->NotifyStoreLoaded();
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());
528 #endif // !defined(OS_ANDROID)
530 TEST_F(UserPolicySigninServiceTest, SignOutAfterInit) {
531 EXPECT_CALL(*mock_store_, Clear());
532 // Set the user as signed in.
533 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
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());
542 // UserCloudPolicyManager should be initialized.
543 ASSERT_TRUE(manager_->core()->service());
546 SigninManagerFactory::GetForProfile(profile_.get())->SignOut();
548 // UserCloudPolicyManager should be shut down.
549 ASSERT_FALSE(manager_->core()->service());
552 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
553 UserPolicySigninService* signin_service =
554 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
555 RegisterPolicyClientWithCallback(signin_service);
556 Mock::VerifyAndClearExpectations(this);
558 // UserCloudPolicyManager should not be initialized.
559 ASSERT_FALSE(manager_->core()->service());
560 ASSERT_TRUE(IsRequestActive());
561 EXPECT_FALSE(register_completed_);
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"));
569 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
570 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
571 fetcher->delegate()->OnURLFetchComplete(fetcher);
574 EXPECT_TRUE(register_completed_);
575 EXPECT_FALSE(created_client_.get());
576 EXPECT_FALSE(IsRequestActive());
579 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
580 UserPolicySigninService* signin_service =
581 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
582 RegisterPolicyClientWithCallback(signin_service);
584 // UserCloudPolicyManager should not be initialized.
585 ASSERT_FALSE(manager_->core()->service());
586 ASSERT_TRUE(IsRequestActive());
588 // Cause the access token request to succeed.
589 MakeOAuthTokenFetchSucceed();
591 // Should be a follow-up fetch to check the hosted-domain status.
592 ASSERT_TRUE(IsRequestActive());
593 Mock::VerifyAndClearExpectations(this);
595 EXPECT_FALSE(register_completed_);
597 // Report that the user is not on a hosted domain - callback should be
598 // invoked reporting a failed fetch.
599 ReportHostedDomainStatus(false);
601 // Since this is not a hosted domain, we should not issue a request for a
603 EXPECT_TRUE(register_completed_);
604 EXPECT_FALSE(created_client_.get());
605 ASSERT_FALSE(IsRequestActive());
608 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
609 UserPolicySigninService* signin_service =
610 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
611 RegisterPolicyClientWithCallback(signin_service);
613 // UserCloudPolicyManager should not be initialized.
614 ASSERT_FALSE(manager_->core()->service());
616 // Mimic successful oauth token fetch.
617 MakeOAuthTokenFetchSucceed();
619 EXPECT_FALSE(register_completed_);
621 // When the user is from a hosted domain, this should kick off client
623 MockDeviceManagementJob* register_request = NULL;
624 EXPECT_CALL(device_management_service_,
625 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
626 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
627 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
630 // Now mimic the user being a hosted domain - this should cause a Register()
632 ReportHostedDomainStatus(true);
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_);
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());
647 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
648 UserPolicySigninService* signin_service =
649 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
650 RegisterPolicyClientWithCallback(signin_service);
652 // Mimic successful oauth token fetch.
653 MakeOAuthTokenFetchSucceed();
655 // When the user is from a hosted domain, this should kick off client
657 MockDeviceManagementJob* register_request = NULL;
658 EXPECT_CALL(device_management_service_,
659 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
660 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
661 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
664 // Now mimic the user being a hosted domain - this should cause a Register()
666 ReportHostedDomainStatus(true);
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_);
674 em::DeviceManagementResponse registration_blob;
675 registration_blob.mutable_register_response()->set_device_management_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());
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");
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(_, _, _, _, _, _, _))
700 UserPolicySigninService* signin_service =
701 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
702 signin_service->FetchPolicyForSignedInUser(
704 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
705 base::Unretained(this)));
706 ASSERT_TRUE(fetch_request);
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());
716 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
717 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
720 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
721 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
723 EXPECT_CALL(*mock_store_, Clear());
724 signin_manager_->ForceSignOut();
725 ASSERT_FALSE(manager_->core()->service());
727 // Now sign in again.
728 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
731 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
732 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
734 ASSERT_TRUE(manager_->IsClientRegistered());
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(_, _, _, _, _, _, _))
743 manager_->RefreshPolicies();
744 Mock::VerifyAndClearExpectations(this);
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());
754 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
755 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
757 EXPECT_TRUE(manager_->IsClientRegistered());
758 #if !defined(OS_ANDROID)
759 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
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(_, _, _, _, _, _, _))
769 manager_->RefreshPolicies();
770 Mock::VerifyAndClearExpectations(this);
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());
787 } // namespace policy