1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/files/file_path.h"
6 #include "base/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"
49 #if defined(OS_ANDROID)
50 #include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
52 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
55 namespace em = enterprise_management;
57 using testing::AnyNumber;
65 const char kTestUser[] = "testuser@test.com";
67 #if !defined(OS_ANDROID)
68 const char kValidTokenResponse[] =
70 " \"access_token\": \"at1\","
71 " \"expires_in\": 3600,"
72 " \"token_type\": \"Bearer\""
76 const char kHostedDomainResponse[] =
78 " \"domain\": \"test.com\""
81 class SigninManagerFake : public FakeSigninManager {
83 explicit SigninManagerFake(Profile* profile)
84 : FakeSigninManager(profile) {
89 // Allow signing out now.
90 prohibit_signout_ = false;
94 static KeyedService* Build(content::BrowserContext* profile) {
95 return new SigninManagerFake(static_cast<Profile*>(profile));
99 UserCloudPolicyManager* BuildCloudPolicyManager(
100 content::BrowserContext* context) {
101 MockUserCloudPolicyStore *store = new MockUserCloudPolicyStore();
102 EXPECT_CALL(*store, Load()).Times(AnyNumber());
104 return new UserCloudPolicyManager(
105 scoped_ptr<UserCloudPolicyStore>(store),
107 scoped_ptr<CloudExternalDataManager>(),
108 base::MessageLoopProxy::current(),
109 base::MessageLoopProxy::current(),
110 base::MessageLoopProxy::current());
113 class UserPolicySigninServiceTest : public testing::Test {
115 UserPolicySigninServiceTest()
117 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
118 register_completed_(false) {}
120 MOCK_METHOD1(OnPolicyRefresh, void(bool));
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;
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");
137 service->RegisterForPolicy(
139 #if !defined(OS_ANDROID)
142 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
143 base::Unretained(this)));
144 ASSERT_TRUE(IsRequestActive());
147 virtual void SetUp() OVERRIDE {
148 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
149 &device_management_service_);
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());
159 g_browser_process->browser_policy_connector()->Init(
160 local_state_.get(), system_request_context_getter_);
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());
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);
182 profile_ = builder.Build().Pass();
183 url_factory_.set_remove_fetcher_on_delete(true);
185 signin_manager_ = static_cast<SigninManagerFake*>(
186 SigninManagerFactory::GetForProfile(profile_.get()));
187 // Tests are responsible for freeing the UserCloudPolicyManager instances
189 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
191 manager_->Init(&schema_registry_);
192 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
193 manager_->core()->store());
197 Mock::VerifyAndClearExpectations(mock_store_);
200 virtual void TearDown() OVERRIDE {
201 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
202 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
203 // Free the profile before we clear out the browser prefs.
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();
214 virtual void AddProfile() {
215 // For this test, the user should not be signed in yet.
216 DCHECK(signin_manager_->GetAuthenticatedUsername().empty());
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());
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());
229 FakeProfileOAuth2TokenService* GetTokenService() {
230 ProfileOAuth2TokenService* service =
231 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
232 return static_cast<FakeProfileOAuth2TokenService*>(service);
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())
242 return url_factory_.GetFetcherByID(0) ||
243 url_factory_.GetFetcherByID(gaia::GaiaOAuthClient::kUrlFetcherId);
246 void MakeOAuthTokenFetchSucceed() {
247 ASSERT_TRUE(IsRequestActive());
248 #if defined(OS_ANDROID)
249 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
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);
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);
268 void TestSuccessfulSignin() {
269 UserPolicySigninService* signin_service =
270 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
271 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
272 RegisterPolicyClientWithCallback(signin_service);
274 // Mimic successful oauth token fetch.
275 MakeOAuthTokenFetchSucceed();
277 // When the user is from a hosted domain, this should kick off client
279 MockDeviceManagementJob* register_request = NULL;
280 EXPECT_CALL(device_management_service_,
281 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
282 .WillOnce(device_management_service_.CreateAsyncJob(
284 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
287 // Now mimic the user being a hosted domain - this should cause a Register()
289 ReportHostedDomainStatus(true);
291 // Should have no more outstanding requests.
292 ASSERT_FALSE(IsRequestActive());
293 Mock::VerifyAndClearExpectations(this);
294 ASSERT_TRUE(register_request);
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(
302 registration_blob.mutable_register_response()->set_enrollment_type(
303 em::DeviceRegisterResponse::ENTERPRISE);
304 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
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);
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(_, _, _, _, _, _, _))
319 signin_service->FetchPolicyForSignedInUser(
323 profile_->GetRequestContext(),
324 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
325 base::Unretained(this)));
327 Mock::VerifyAndClearExpectations(this);
328 ASSERT_TRUE(fetch_request);
330 // UserCloudPolicyManager should now be initialized.
331 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
332 ASSERT_TRUE(manager_->core()->service());
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);
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);
349 // Complete the store which should cause the policy fetch callback to be
351 mock_store_->NotifyStoreLoaded();
352 Mock::VerifyAndClearExpectations(this);
355 scoped_ptr<TestingProfile> profile_;
356 MockUserCloudPolicyStore* mock_store_; // Not owned.
357 SchemaRegistry schema_registry_;
358 scoped_ptr<UserCloudPolicyManager> manager_;
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_;
364 net::TestURLFetcherFactory url_factory_;
366 SigninManagerFake* signin_manager_;
368 // Used in conjunction with OnRegisterCompleted() to test client registration
370 std::string dm_token_;
371 std::string client_id_;
373 // True if OnRegisterCompleted() was called.
374 bool register_completed_;
376 // Weak ptr to the MockDeviceManagementService (object is owned by the
377 // BrowserPolicyConnector).
378 MockDeviceManagementService device_management_service_;
380 scoped_ptr<TestingPrefServiceSimple> local_state_;
381 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
384 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
386 virtual void AddProfile() OVERRIDE {
387 // UserCloudPolicyManager should not be initialized.
388 ASSERT_FALSE(manager_->core()->service());
390 // Set the user as signed in.
391 SigninManagerFactory::GetForProfile(profile_.get())->
392 SetAuthenticatedUsername(kTestUser);
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());
402 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
403 // Make sure user is not signed in.
404 ASSERT_TRUE(SigninManagerFactory::GetForProfile(profile_.get())->
405 GetAuthenticatedUsername().empty());
407 // UserCloudPolicyManager should not be initialized.
408 ASSERT_FALSE(manager_->core()->service());
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
414 #if !defined(OS_ANDROID)
416 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
417 // UserCloudPolicyManager should be initialized.
418 ASSERT_TRUE(manager_->core()->service());
420 // Complete initialization of the store.
421 mock_store_->NotifyStoreLoaded();
423 // No oauth access token yet, so client registration should be deferred.
424 ASSERT_FALSE(IsRequestActive());
426 // Make oauth token available.
427 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
428 "oauth_login_refresh_token");
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());
435 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
436 // UserCloudPolicyManager should be initialized.
437 ASSERT_TRUE(manager_->core()->service());
439 // Complete initialization of the store.
440 mock_store_->NotifyStoreLoaded();
442 // No oauth access token yet, so client registration should be deferred.
443 ASSERT_FALSE(IsRequestActive());
445 // Make oauth token available.
446 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
447 "oauth_login_refresh_token");
449 // Client registration should be in progress since we now have an oauth token.
450 ASSERT_TRUE(IsRequestActive());
452 // Now fail the access token fetch.
453 GoogleServiceAuthError error(
454 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
455 GetTokenService()->IssueErrorForAllPendingRequests(error);
456 ASSERT_FALSE(IsRequestActive());
459 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
460 // UserCloudPolicyManager should not be initialized since there is no
462 ASSERT_FALSE(manager_->core()->service());
464 // Now sign in the user.
465 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
468 // Complete initialization of the store.
469 mock_store_->NotifyStoreLoaded();
471 // Make oauth token available.
472 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
473 "oauth_login_refresh_token");
475 // UserCloudPolicyManager should be initialized.
476 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
477 ASSERT_TRUE(manager_->core()->service());
479 // Client registration should be in progress since we have an oauth token.
480 ASSERT_TRUE(IsRequestActive());
483 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
484 // UserCloudPolicyManager should not be initialized since there is no
486 ASSERT_FALSE(manager_->core()->service());
488 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
489 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
490 "non_enterprise_user@gmail.com");
492 // Complete initialization of the store.
493 mock_store_->NotifyStoreLoaded();
495 // Make oauth token available.
496 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
497 "oauth_login_refresh_token");
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());
505 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
506 // UserCloudPolicyManager should not be initialized since there is no
508 ASSERT_FALSE(manager_->core()->service());
510 // Now sign in the user.
511 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
514 // Make oauth token available.
515 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
516 "oauth_login_refresh_token");
518 // UserCloudPolicyManager should be initialized.
519 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
520 ASSERT_TRUE(manager_->core()->service());
522 // Client registration should not be in progress since the store is not
524 ASSERT_FALSE(IsRequestActive());
526 // Complete initialization of the store with no policy (unregistered client).
527 mock_store_->NotifyStoreLoaded();
529 // Client registration should be in progress since we have an oauth token.
530 ASSERT_TRUE(IsRequestActive());
533 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
534 // UserCloudPolicyManager should not be initialized since there is no
536 ASSERT_FALSE(manager_->core()->service());
538 // Now sign in the user.
539 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
542 // Make oauth token available.
543 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
544 "oauth_login_refresh_token");
546 // UserCloudPolicyManager should be initialized.
547 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
548 ASSERT_TRUE(manager_->core()->service());
550 // Client registration should not be in progress since the store is not
552 ASSERT_FALSE(manager_->IsClientRegistered());
553 ASSERT_FALSE(IsRequestActive());
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");
559 // Complete initialization of the store.
560 mock_store_->NotifyStoreLoaded();
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());
568 #endif // !defined(OS_ANDROID)
570 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
571 // UserCloudPolicyManager should be initialized.
572 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
573 ASSERT_TRUE(manager_->core()->service());
575 // Signing out will clear the policy from the store.
576 EXPECT_CALL(*mock_store_, Clear());
579 SigninManagerFactory::GetForProfile(profile_.get())->SignOut();
581 // UserCloudPolicyManager should be shut down.
582 ASSERT_FALSE(manager_->core()->service());
585 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
586 UserPolicySigninService* signin_service =
587 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
588 RegisterPolicyClientWithCallback(signin_service);
589 Mock::VerifyAndClearExpectations(this);
591 // UserCloudPolicyManager should not be initialized.
592 ASSERT_FALSE(manager_->core()->service());
593 ASSERT_TRUE(IsRequestActive());
594 EXPECT_FALSE(register_completed_);
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"));
602 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
603 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
604 fetcher->delegate()->OnURLFetchComplete(fetcher);
607 EXPECT_TRUE(register_completed_);
608 EXPECT_TRUE(dm_token_.empty());
609 EXPECT_FALSE(IsRequestActive());
612 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
613 UserPolicySigninService* signin_service =
614 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
615 RegisterPolicyClientWithCallback(signin_service);
617 // UserCloudPolicyManager should not be initialized.
618 ASSERT_FALSE(manager_->core()->service());
619 ASSERT_TRUE(IsRequestActive());
621 // Cause the access token request to succeed.
622 MakeOAuthTokenFetchSucceed();
624 // Should be a follow-up fetch to check the hosted-domain status.
625 ASSERT_TRUE(IsRequestActive());
626 Mock::VerifyAndClearExpectations(this);
628 EXPECT_FALSE(register_completed_);
630 // Report that the user is not on a hosted domain - callback should be
631 // invoked reporting a failed fetch.
632 ReportHostedDomainStatus(false);
634 // Since this is not a hosted domain, we should not issue a request for a
636 EXPECT_TRUE(register_completed_);
637 EXPECT_TRUE(dm_token_.empty());
638 ASSERT_FALSE(IsRequestActive());
641 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
642 UserPolicySigninService* signin_service =
643 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
644 RegisterPolicyClientWithCallback(signin_service);
646 // UserCloudPolicyManager should not be initialized.
647 ASSERT_FALSE(manager_->core()->service());
649 // Mimic successful oauth token fetch.
650 MakeOAuthTokenFetchSucceed();
652 EXPECT_FALSE(register_completed_);
654 // When the user is from a hosted domain, this should kick off client
656 MockDeviceManagementJob* register_request = NULL;
657 EXPECT_CALL(device_management_service_,
658 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
659 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
660 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
663 // Now mimic the user being a hosted domain - this should cause a Register()
665 ReportHostedDomainStatus(true);
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_);
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());
680 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
681 UserPolicySigninService* signin_service =
682 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
683 RegisterPolicyClientWithCallback(signin_service);
685 // Mimic successful oauth token fetch.
686 MakeOAuthTokenFetchSucceed();
688 // When the user is from a hosted domain, this should kick off client
690 MockDeviceManagementJob* register_request = NULL;
691 EXPECT_CALL(device_management_service_,
692 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
693 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
694 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
697 // Now mimic the user being a hosted domain - this should cause a Register()
699 ReportHostedDomainStatus(true);
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_);
707 em::DeviceManagementResponse registration_blob;
708 std::string expected_dm_token = "dm_token";
709 registration_blob.mutable_register_response()->set_device_management_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());
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(_, _, _, _, _, _, _))
729 UserPolicySigninService* signin_service =
730 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
731 signin_service->FetchPolicyForSignedInUser(
735 profile_->GetRequestContext(),
736 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
737 base::Unretained(this)));
738 ASSERT_TRUE(fetch_request);
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());
745 // UserCloudPolicyManager should be initialized.
746 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
747 ASSERT_TRUE(manager_->core()->service());
750 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
751 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
754 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
755 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
757 EXPECT_CALL(*mock_store_, Clear());
758 signin_manager_->ForceSignOut();
759 ASSERT_FALSE(manager_->core()->service());
761 // Now sign in again.
762 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
765 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
766 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
768 ASSERT_TRUE(manager_->IsClientRegistered());
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(_, _, _, _, _, _, _))
777 manager_->RefreshPolicies();
778 Mock::VerifyAndClearExpectations(this);
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());
788 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
789 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
791 EXPECT_TRUE(manager_->IsClientRegistered());
792 #if !defined(OS_ANDROID)
793 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
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(_, _, _, _, _, _, _))
803 manager_->RefreshPolicies();
804 Mock::VerifyAndClearExpectations(this);
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());
821 } // namespace policy