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/google_service_auth_error.h"
40 #include "net/http/http_status_code.h"
41 #include "net/url_request/test_url_fetcher_factory.h"
42 #include "net/url_request/url_request_context_getter.h"
43 #include "net/url_request/url_request_status.h"
44 #include "net/url_request/url_request_test_util.h"
45 #include "testing/gmock/include/gmock/gmock.h"
46 #include "testing/gtest/include/gtest/gtest.h"
48 #if defined(OS_ANDROID)
49 #include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
51 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
54 namespace em = enterprise_management;
56 using testing::AnyNumber;
64 const char kTestUser[] = "testuser@test.com";
66 #if !defined(OS_ANDROID)
67 const char kValidTokenResponse[] =
69 " \"access_token\": \"at1\","
70 " \"expires_in\": 3600,"
71 " \"token_type\": \"Bearer\""
75 const char kHostedDomainResponse[] =
77 " \"hd\": \"test.com\""
80 class SigninManagerFake : public FakeSigninManager {
82 explicit SigninManagerFake(Profile* profile)
83 : FakeSigninManager(profile) {
88 // Allow signing out now.
89 prohibit_signout_ = false;
90 SignOut(signin_metrics::SIGNOUT_TEST);
93 static KeyedService* Build(content::BrowserContext* profile) {
94 return new SigninManagerFake(static_cast<Profile*>(profile));
98 UserCloudPolicyManager* BuildCloudPolicyManager(
99 content::BrowserContext* context) {
100 MockUserCloudPolicyStore *store = new MockUserCloudPolicyStore();
101 EXPECT_CALL(*store, Load()).Times(AnyNumber());
103 return new UserCloudPolicyManager(
104 scoped_ptr<UserCloudPolicyStore>(store),
106 scoped_ptr<CloudExternalDataManager>(),
107 base::MessageLoopProxy::current(),
108 base::MessageLoopProxy::current(),
109 base::MessageLoopProxy::current());
112 class UserPolicySigninServiceTest : public testing::Test {
114 UserPolicySigninServiceTest()
116 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
117 register_completed_(false) {}
119 MOCK_METHOD1(OnPolicyRefresh, void(bool));
121 void OnRegisterCompleted(const std::string& dm_token,
122 const std::string& client_id) {
123 register_completed_ = true;
124 dm_token_ = dm_token;
125 client_id_ = client_id;
128 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
129 // Policy client registration on Android depends on Token Service having
130 // a valid login token, while on other platforms, the login refresh token
131 // is specified directly.
132 #if defined(OS_ANDROID)
133 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
134 "oauth2_login_refresh_token");
136 service->RegisterForPolicy(
138 #if !defined(OS_ANDROID)
141 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
142 base::Unretained(this)));
143 ASSERT_TRUE(IsRequestActive());
146 virtual void SetUp() OVERRIDE {
147 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
148 &device_management_service_);
150 local_state_.reset(new TestingPrefServiceSimple);
151 chrome::RegisterLocalState(local_state_->registry());
152 system_request_context_getter_ = new net::TestURLRequestContextGetter(
153 base::MessageLoopProxy::current());
154 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
155 system_request_context_getter_.get());
156 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
158 g_browser_process->browser_policy_connector()->Init(
159 local_state_.get(), system_request_context_getter_);
161 // Create a testing profile with cloud-policy-on-signin enabled, and bring
162 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
163 scoped_ptr<TestingPrefServiceSyncable> prefs(
164 new TestingPrefServiceSyncable());
165 chrome::RegisterUserProfilePrefs(prefs->registry());
167 // UserCloudPolicyManagerFactory isn't a real
168 // BrowserContextKeyedServiceFactory (it derives from
169 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
170 // instances) so we have to inject our testing factory via a special
171 // API before creating the profile.
172 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
173 BuildCloudPolicyManager);
174 TestingProfile::Builder builder;
175 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
176 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
177 SigninManagerFake::Build);
178 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
179 BuildFakeProfileOAuth2TokenService);
181 profile_ = builder.Build().Pass();
182 url_factory_.set_remove_fetcher_on_delete(true);
184 signin_manager_ = static_cast<SigninManagerFake*>(
185 SigninManagerFactory::GetForProfile(profile_.get()));
186 // Tests are responsible for freeing the UserCloudPolicyManager instances
188 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
190 manager_->Init(&schema_registry_);
191 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
192 manager_->core()->store());
196 Mock::VerifyAndClearExpectations(mock_store_);
199 virtual void TearDown() OVERRIDE {
200 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
201 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
202 // Free the profile before we clear out the browser prefs.
204 TestingBrowserProcess* testing_browser_process =
205 TestingBrowserProcess::GetGlobal();
206 testing_browser_process->SetLocalState(NULL);
207 local_state_.reset();
208 testing_browser_process->SetBrowserPolicyConnector(NULL);
209 base::RunLoop run_loop;
210 run_loop.RunUntilIdle();
213 virtual void AddProfile() {
214 // For this test, the user should not be signed in yet.
215 DCHECK(!signin_manager_->IsAuthenticated());
217 // Initializing UserPolicySigninService while the user is not signed in
218 // should result in the store being cleared to remove any lingering policy.
219 EXPECT_CALL(*mock_store_, Clear());
221 // Let the SigninService know that the profile has been created.
222 content::NotificationService::current()->Notify(
223 chrome::NOTIFICATION_PROFILE_ADDED,
224 content::Source<Profile>(profile_.get()),
225 content::NotificationService::NoDetails());
228 FakeProfileOAuth2TokenService* GetTokenService() {
229 ProfileOAuth2TokenService* service =
230 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
231 return static_cast<FakeProfileOAuth2TokenService*>(service);
234 bool IsRequestActive() {
235 if (!GetTokenService()->GetPendingRequests().empty())
237 return url_factory_.GetFetcherByID(0);
240 void MakeOAuthTokenFetchSucceed() {
241 ASSERT_TRUE(IsRequestActive());
242 #if defined(OS_ANDROID)
243 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
246 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
247 fetcher->set_response_code(net::HTTP_OK);
248 fetcher->SetResponseString(kValidTokenResponse);
249 fetcher->delegate()->OnURLFetchComplete(fetcher);
253 void ReportHostedDomainStatus(bool is_hosted_domain) {
254 ASSERT_TRUE(IsRequestActive());
255 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
256 fetcher->set_response_code(net::HTTP_OK);
257 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
258 fetcher->delegate()->OnURLFetchComplete(fetcher);
261 void TestSuccessfulSignin() {
262 UserPolicySigninService* signin_service =
263 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
264 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
265 RegisterPolicyClientWithCallback(signin_service);
267 // Mimic successful oauth token fetch.
268 MakeOAuthTokenFetchSucceed();
270 // When the user is from a hosted domain, this should kick off client
272 MockDeviceManagementJob* register_request = NULL;
273 EXPECT_CALL(device_management_service_,
274 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
275 .WillOnce(device_management_service_.CreateAsyncJob(
277 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
280 // Now mimic the user being a hosted domain - this should cause a Register()
282 ReportHostedDomainStatus(true);
284 // Should have no more outstanding requests.
285 ASSERT_FALSE(IsRequestActive());
286 Mock::VerifyAndClearExpectations(this);
287 ASSERT_TRUE(register_request);
289 // Mimic successful client registration - this should register the client
290 // and invoke the callback.
291 em::DeviceManagementResponse registration_blob;
292 std::string expected_dm_token = "dm_token";
293 registration_blob.mutable_register_response()->set_device_management_token(
295 registration_blob.mutable_register_response()->set_enrollment_type(
296 em::DeviceRegisterResponse::ENTERPRISE);
297 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
299 // UserCloudPolicyManager should not be initialized yet.
300 ASSERT_FALSE(manager_->core()->service());
301 EXPECT_TRUE(register_completed_);
302 EXPECT_EQ(dm_token_, expected_dm_token);
304 // Now call to fetch policy - this should fire off a fetch request.
305 MockDeviceManagementJob* fetch_request = NULL;
306 EXPECT_CALL(device_management_service_,
307 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
308 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
309 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
312 signin_service->FetchPolicyForSignedInUser(
316 profile_->GetRequestContext(),
317 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
318 base::Unretained(this)));
320 Mock::VerifyAndClearExpectations(this);
321 ASSERT_TRUE(fetch_request);
323 // UserCloudPolicyManager should now be initialized.
324 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
325 ASSERT_TRUE(manager_->core()->service());
327 // Make the policy fetch succeed - this should result in a write to the
328 // store and ultimately result in a call to OnPolicyRefresh().
329 EXPECT_CALL(*mock_store_, Store(_));
330 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
332 // Create a fake policy blob to deliver to the client.
333 em::DeviceManagementResponse policy_blob;
334 em::PolicyData policy_data;
335 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
336 em::PolicyFetchResponse* policy_response =
337 policy_blob.mutable_policy_response()->add_response();
338 ASSERT_TRUE(policy_data.SerializeToString(
339 policy_response->mutable_policy_data()));
340 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
342 // Complete the store which should cause the policy fetch callback to be
344 mock_store_->NotifyStoreLoaded();
345 Mock::VerifyAndClearExpectations(this);
348 scoped_ptr<TestingProfile> profile_;
349 MockUserCloudPolicyStore* mock_store_; // Not owned.
350 SchemaRegistry schema_registry_;
351 scoped_ptr<UserCloudPolicyManager> manager_;
353 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
354 // various components asynchronously via tasks, so create fake threads here.
355 content::TestBrowserThreadBundle thread_bundle_;
357 net::TestURLFetcherFactory url_factory_;
359 SigninManagerFake* signin_manager_;
361 // Used in conjunction with OnRegisterCompleted() to test client registration
363 std::string dm_token_;
364 std::string client_id_;
366 // True if OnRegisterCompleted() was called.
367 bool register_completed_;
369 // Weak ptr to the MockDeviceManagementService (object is owned by the
370 // BrowserPolicyConnector).
371 MockDeviceManagementService device_management_service_;
373 scoped_ptr<TestingPrefServiceSimple> local_state_;
374 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
377 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
379 virtual void AddProfile() OVERRIDE {
380 // UserCloudPolicyManager should not be initialized.
381 ASSERT_FALSE(manager_->core()->service());
383 // Set the user as signed in.
384 SigninManagerFactory::GetForProfile(profile_.get())->
385 SetAuthenticatedUsername(kTestUser);
387 // Let the SigninService know that the profile has been created.
388 content::NotificationService::current()->Notify(
389 chrome::NOTIFICATION_PROFILE_ADDED,
390 content::Source<Profile>(profile_.get()),
391 content::NotificationService::NoDetails());
395 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
396 // Make sure user is not signed in.
397 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
400 // UserCloudPolicyManager should not be initialized.
401 ASSERT_FALSE(manager_->core()->service());
404 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
405 // token after signin. Revisit this after figuring how to handle that on
407 #if !defined(OS_ANDROID)
409 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
410 // UserCloudPolicyManager should be initialized.
411 ASSERT_TRUE(manager_->core()->service());
413 // Complete initialization of the store.
414 mock_store_->NotifyStoreLoaded();
416 // No oauth access token yet, so client registration should be deferred.
417 ASSERT_FALSE(IsRequestActive());
419 // Make oauth token available.
420 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
421 "oauth_login_refresh_token");
423 // Client registration should be in progress since we now have an oauth token.
424 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
425 ASSERT_TRUE(IsRequestActive());
428 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
429 // UserCloudPolicyManager should be initialized.
430 ASSERT_TRUE(manager_->core()->service());
432 // Complete initialization of the store.
433 mock_store_->NotifyStoreLoaded();
435 // No oauth access token yet, so client registration should be deferred.
436 ASSERT_FALSE(IsRequestActive());
438 // Make oauth token available.
439 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
440 "oauth_login_refresh_token");
442 // Client registration should be in progress since we now have an oauth token.
443 ASSERT_TRUE(IsRequestActive());
445 // Now fail the access token fetch.
446 GoogleServiceAuthError error(
447 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
448 GetTokenService()->IssueErrorForAllPendingRequests(error);
449 ASSERT_FALSE(IsRequestActive());
452 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
453 // UserCloudPolicyManager should not be initialized since there is no
455 ASSERT_FALSE(manager_->core()->service());
457 // Now sign in the user.
458 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
461 // Complete initialization of the store.
462 mock_store_->NotifyStoreLoaded();
464 // Make oauth token available.
465 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
466 "oauth_login_refresh_token");
468 // UserCloudPolicyManager should be initialized.
469 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
470 ASSERT_TRUE(manager_->core()->service());
472 // Client registration should be in progress since we have an oauth token.
473 ASSERT_TRUE(IsRequestActive());
476 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
477 // UserCloudPolicyManager should not be initialized since there is no
479 ASSERT_FALSE(manager_->core()->service());
481 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
482 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
483 "non_enterprise_user@gmail.com");
485 // Complete initialization of the store.
486 mock_store_->NotifyStoreLoaded();
488 // Make oauth token available.
489 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
490 "oauth_login_refresh_token");
492 // UserCloudPolicyManager should not be initialized and there should be no
493 // DMToken request active.
494 ASSERT_TRUE(!manager_->core()->service());
495 ASSERT_FALSE(IsRequestActive());
498 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
499 // UserCloudPolicyManager should not be initialized since there is no
501 ASSERT_FALSE(manager_->core()->service());
503 // Now sign in the user.
504 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
507 // Make oauth token available.
508 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
509 "oauth_login_refresh_token");
511 // UserCloudPolicyManager should be initialized.
512 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
513 ASSERT_TRUE(manager_->core()->service());
515 // Client registration should not be in progress since the store is not
517 ASSERT_FALSE(IsRequestActive());
519 // Complete initialization of the store with no policy (unregistered client).
520 mock_store_->NotifyStoreLoaded();
522 // Client registration should be in progress since we have an oauth token.
523 ASSERT_TRUE(IsRequestActive());
526 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
527 // UserCloudPolicyManager should not be initialized since there is no
529 ASSERT_FALSE(manager_->core()->service());
531 // Now sign in the user.
532 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
535 // Make oauth token available.
536 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
537 "oauth_login_refresh_token");
539 // UserCloudPolicyManager should be initialized.
540 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
541 ASSERT_TRUE(manager_->core()->service());
543 // Client registration should not be in progress since the store is not
545 ASSERT_FALSE(manager_->IsClientRegistered());
546 ASSERT_FALSE(IsRequestActive());
548 mock_store_->policy_.reset(new enterprise_management::PolicyData());
549 mock_store_->policy_->set_request_token("fake token");
550 mock_store_->policy_->set_device_id("fake client id");
552 // Complete initialization of the store.
553 mock_store_->NotifyStoreLoaded();
555 // Client registration should not be in progress since the client should be
556 // already registered.
557 ASSERT_TRUE(manager_->IsClientRegistered());
558 ASSERT_FALSE(IsRequestActive());
561 #endif // !defined(OS_ANDROID)
563 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
564 // UserCloudPolicyManager should be initialized.
565 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
566 ASSERT_TRUE(manager_->core()->service());
568 // Signing out will clear the policy from the store.
569 EXPECT_CALL(*mock_store_, Clear());
572 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
573 signin_metrics::SIGNOUT_TEST);
575 // UserCloudPolicyManager should be shut down.
576 ASSERT_FALSE(manager_->core()->service());
579 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
580 UserPolicySigninService* signin_service =
581 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
582 RegisterPolicyClientWithCallback(signin_service);
583 Mock::VerifyAndClearExpectations(this);
585 // UserCloudPolicyManager should not be initialized.
586 ASSERT_FALSE(manager_->core()->service());
587 ASSERT_TRUE(IsRequestActive());
588 EXPECT_FALSE(register_completed_);
590 // Cause the access token fetch to fail - callback should be invoked.
591 #if defined(OS_ANDROID)
592 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
593 GetTokenService()->IssueErrorForAllPendingRequests(
594 GoogleServiceAuthError::FromServiceError("fail"));
596 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
597 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
598 fetcher->delegate()->OnURLFetchComplete(fetcher);
601 EXPECT_TRUE(register_completed_);
602 EXPECT_TRUE(dm_token_.empty());
603 EXPECT_FALSE(IsRequestActive());
606 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
607 UserPolicySigninService* signin_service =
608 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
609 RegisterPolicyClientWithCallback(signin_service);
611 // UserCloudPolicyManager should not be initialized.
612 ASSERT_FALSE(manager_->core()->service());
613 ASSERT_TRUE(IsRequestActive());
615 // Cause the access token request to succeed.
616 MakeOAuthTokenFetchSucceed();
618 // Should be a follow-up fetch to check the hosted-domain status.
619 ASSERT_TRUE(IsRequestActive());
620 Mock::VerifyAndClearExpectations(this);
622 EXPECT_FALSE(register_completed_);
624 // Report that the user is not on a hosted domain - callback should be
625 // invoked reporting a failed fetch.
626 ReportHostedDomainStatus(false);
628 // Since this is not a hosted domain, we should not issue a request for a
630 EXPECT_TRUE(register_completed_);
631 EXPECT_TRUE(dm_token_.empty());
632 ASSERT_FALSE(IsRequestActive());
635 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
636 UserPolicySigninService* signin_service =
637 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
638 RegisterPolicyClientWithCallback(signin_service);
640 // UserCloudPolicyManager should not be initialized.
641 ASSERT_FALSE(manager_->core()->service());
643 // Mimic successful oauth token fetch.
644 MakeOAuthTokenFetchSucceed();
646 EXPECT_FALSE(register_completed_);
648 // When the user is from a hosted domain, this should kick off client
650 MockDeviceManagementJob* register_request = NULL;
651 EXPECT_CALL(device_management_service_,
652 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
653 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
654 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
657 // Now mimic the user being a hosted domain - this should cause a Register()
659 ReportHostedDomainStatus(true);
661 // Should have no more outstanding requests.
662 ASSERT_FALSE(IsRequestActive());
663 Mock::VerifyAndClearExpectations(this);
664 ASSERT_TRUE(register_request);
665 EXPECT_FALSE(register_completed_);
667 // Make client registration fail (hosted domain user that is not managed).
668 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
669 em::DeviceManagementResponse());
670 EXPECT_TRUE(register_completed_);
671 EXPECT_TRUE(dm_token_.empty());
674 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
675 UserPolicySigninService* signin_service =
676 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
677 RegisterPolicyClientWithCallback(signin_service);
679 // Mimic successful oauth token fetch.
680 MakeOAuthTokenFetchSucceed();
682 // When the user is from a hosted domain, this should kick off client
684 MockDeviceManagementJob* register_request = NULL;
685 EXPECT_CALL(device_management_service_,
686 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
687 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
688 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
691 // Now mimic the user being a hosted domain - this should cause a Register()
693 ReportHostedDomainStatus(true);
695 // Should have no more outstanding requests.
696 ASSERT_FALSE(IsRequestActive());
697 Mock::VerifyAndClearExpectations(this);
698 ASSERT_TRUE(register_request);
699 EXPECT_FALSE(register_completed_);
701 em::DeviceManagementResponse registration_blob;
702 std::string expected_dm_token = "dm_token";
703 registration_blob.mutable_register_response()->set_device_management_token(
705 registration_blob.mutable_register_response()->set_enrollment_type(
706 em::DeviceRegisterResponse::ENTERPRISE);
707 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
708 Mock::VerifyAndClearExpectations(this);
709 EXPECT_TRUE(register_completed_);
710 EXPECT_EQ(dm_token_, expected_dm_token);
711 // UserCloudPolicyManager should not be initialized.
712 ASSERT_FALSE(manager_->core()->service());
715 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
716 // Initiate a policy fetch request.
717 MockDeviceManagementJob* fetch_request = NULL;
718 EXPECT_CALL(device_management_service_,
719 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
720 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
721 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
723 UserPolicySigninService* signin_service =
724 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
725 signin_service->FetchPolicyForSignedInUser(
729 profile_->GetRequestContext(),
730 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
731 base::Unretained(this)));
732 ASSERT_TRUE(fetch_request);
734 // Make the policy fetch fail.
735 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
736 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
737 em::DeviceManagementResponse());
739 // UserCloudPolicyManager should be initialized.
740 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
741 ASSERT_TRUE(manager_->core()->service());
744 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
745 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
748 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
749 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
751 EXPECT_CALL(*mock_store_, Clear());
752 signin_manager_->ForceSignOut();
753 ASSERT_FALSE(manager_->core()->service());
755 // Now sign in again.
756 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
759 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
760 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
762 ASSERT_TRUE(manager_->IsClientRegistered());
764 // Kick off another policy fetch.
765 MockDeviceManagementJob* fetch_request = NULL;
766 EXPECT_CALL(device_management_service_,
767 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
768 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
769 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
771 manager_->RefreshPolicies();
772 Mock::VerifyAndClearExpectations(this);
774 // Now, fake a transient error from the server on this policy fetch. This
775 // should have no impact on the cached policy.
776 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
777 em::DeviceManagementResponse());
778 base::RunLoop().RunUntilIdle();
779 ASSERT_TRUE(manager_->IsClientRegistered());
782 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
783 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
785 EXPECT_TRUE(manager_->IsClientRegistered());
786 #if !defined(OS_ANDROID)
787 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
790 // Kick off another policy fetch.
791 MockDeviceManagementJob* fetch_request = NULL;
792 EXPECT_CALL(device_management_service_,
793 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
794 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
795 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
797 manager_->RefreshPolicies();
798 Mock::VerifyAndClearExpectations(this);
800 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
801 // indicates that chrome management is disabled and will result in the cached
802 // policy being removed and the manager shut down.
803 EXPECT_CALL(*mock_store_, Clear());
804 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
805 em::DeviceManagementResponse());
806 base::RunLoop().RunUntilIdle();
807 EXPECT_FALSE(manager_->IsClientRegistered());
808 #if !defined(OS_ANDROID)
809 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
815 } // namespace policy