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_wrapper.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.h"
22 #include "chrome/browser/signin/signin_manager_factory.h"
23 #include "chrome/test/base/testing_browser_process.h"
24 #include "chrome/test/base/testing_pref_service_syncable.h"
25 #include "chrome/test/base/testing_profile.h"
26 #include "components/policy/core/browser/browser_policy_connector.h"
27 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
28 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
29 #include "components/policy/core/common/cloud/mock_device_management_service.h"
30 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
31 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
32 #include "components/policy/core/common/schema_registry.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_android.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) {
84 Initialize(profile, NULL);
88 // Allow signing out now.
89 prohibit_signout_ = false;
93 static BrowserContextKeyedService* 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 FakeProfileOAuth2TokenServiceWrapper::Build);
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_->GetAuthenticatedUsername().empty());
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_TRUE(SigninManagerFactory::GetForProfile(profile_.get())->
398 GetAuthenticatedUsername().empty());
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();
574 // UserCloudPolicyManager should be shut down.
575 ASSERT_FALSE(manager_->core()->service());
578 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
579 UserPolicySigninService* signin_service =
580 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
581 RegisterPolicyClientWithCallback(signin_service);
582 Mock::VerifyAndClearExpectations(this);
584 // UserCloudPolicyManager should not be initialized.
585 ASSERT_FALSE(manager_->core()->service());
586 ASSERT_TRUE(IsRequestActive());
587 EXPECT_FALSE(register_completed_);
589 // Cause the access token fetch to fail - callback should be invoked.
590 #if defined(OS_ANDROID)
591 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
592 GetTokenService()->IssueErrorForAllPendingRequests(
593 GoogleServiceAuthError::FromServiceError("fail"));
595 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
596 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
597 fetcher->delegate()->OnURLFetchComplete(fetcher);
600 EXPECT_TRUE(register_completed_);
601 EXPECT_TRUE(dm_token_.empty());
602 EXPECT_FALSE(IsRequestActive());
605 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
606 UserPolicySigninService* signin_service =
607 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
608 RegisterPolicyClientWithCallback(signin_service);
610 // UserCloudPolicyManager should not be initialized.
611 ASSERT_FALSE(manager_->core()->service());
612 ASSERT_TRUE(IsRequestActive());
614 // Cause the access token request to succeed.
615 MakeOAuthTokenFetchSucceed();
617 // Should be a follow-up fetch to check the hosted-domain status.
618 ASSERT_TRUE(IsRequestActive());
619 Mock::VerifyAndClearExpectations(this);
621 EXPECT_FALSE(register_completed_);
623 // Report that the user is not on a hosted domain - callback should be
624 // invoked reporting a failed fetch.
625 ReportHostedDomainStatus(false);
627 // Since this is not a hosted domain, we should not issue a request for a
629 EXPECT_TRUE(register_completed_);
630 EXPECT_TRUE(dm_token_.empty());
631 ASSERT_FALSE(IsRequestActive());
634 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
635 UserPolicySigninService* signin_service =
636 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
637 RegisterPolicyClientWithCallback(signin_service);
639 // UserCloudPolicyManager should not be initialized.
640 ASSERT_FALSE(manager_->core()->service());
642 // Mimic successful oauth token fetch.
643 MakeOAuthTokenFetchSucceed();
645 EXPECT_FALSE(register_completed_);
647 // When the user is from a hosted domain, this should kick off client
649 MockDeviceManagementJob* register_request = NULL;
650 EXPECT_CALL(device_management_service_,
651 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
652 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
653 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
656 // Now mimic the user being a hosted domain - this should cause a Register()
658 ReportHostedDomainStatus(true);
660 // Should have no more outstanding requests.
661 ASSERT_FALSE(IsRequestActive());
662 Mock::VerifyAndClearExpectations(this);
663 ASSERT_TRUE(register_request);
664 EXPECT_FALSE(register_completed_);
666 // Make client registration fail (hosted domain user that is not managed).
667 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
668 em::DeviceManagementResponse());
669 EXPECT_TRUE(register_completed_);
670 EXPECT_TRUE(dm_token_.empty());
673 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
674 UserPolicySigninService* signin_service =
675 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
676 RegisterPolicyClientWithCallback(signin_service);
678 // Mimic successful oauth token fetch.
679 MakeOAuthTokenFetchSucceed();
681 // When the user is from a hosted domain, this should kick off client
683 MockDeviceManagementJob* register_request = NULL;
684 EXPECT_CALL(device_management_service_,
685 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
686 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
687 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
690 // Now mimic the user being a hosted domain - this should cause a Register()
692 ReportHostedDomainStatus(true);
694 // Should have no more outstanding requests.
695 ASSERT_FALSE(IsRequestActive());
696 Mock::VerifyAndClearExpectations(this);
697 ASSERT_TRUE(register_request);
698 EXPECT_FALSE(register_completed_);
700 em::DeviceManagementResponse registration_blob;
701 std::string expected_dm_token = "dm_token";
702 registration_blob.mutable_register_response()->set_device_management_token(
704 registration_blob.mutable_register_response()->set_enrollment_type(
705 em::DeviceRegisterResponse::ENTERPRISE);
706 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
707 Mock::VerifyAndClearExpectations(this);
708 EXPECT_TRUE(register_completed_);
709 EXPECT_EQ(dm_token_, expected_dm_token);
710 // UserCloudPolicyManager should not be initialized.
711 ASSERT_FALSE(manager_->core()->service());
714 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
715 // Initiate a policy fetch request.
716 MockDeviceManagementJob* fetch_request = NULL;
717 EXPECT_CALL(device_management_service_,
718 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
719 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
720 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
722 UserPolicySigninService* signin_service =
723 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
724 signin_service->FetchPolicyForSignedInUser(
728 profile_->GetRequestContext(),
729 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
730 base::Unretained(this)));
731 ASSERT_TRUE(fetch_request);
733 // Make the policy fetch fail.
734 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
735 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
736 em::DeviceManagementResponse());
738 // UserCloudPolicyManager should be initialized.
739 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
740 ASSERT_TRUE(manager_->core()->service());
743 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
744 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
747 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
748 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
750 EXPECT_CALL(*mock_store_, Clear());
751 signin_manager_->ForceSignOut();
752 ASSERT_FALSE(manager_->core()->service());
754 // Now sign in again.
755 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
758 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
759 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
761 ASSERT_TRUE(manager_->IsClientRegistered());
763 // Kick off another policy fetch.
764 MockDeviceManagementJob* fetch_request = NULL;
765 EXPECT_CALL(device_management_service_,
766 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
767 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
768 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
770 manager_->RefreshPolicies();
771 Mock::VerifyAndClearExpectations(this);
773 // Now, fake a transient error from the server on this policy fetch. This
774 // should have no impact on the cached policy.
775 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
776 em::DeviceManagementResponse());
777 base::RunLoop().RunUntilIdle();
778 ASSERT_TRUE(manager_->IsClientRegistered());
781 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
782 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
784 EXPECT_TRUE(manager_->IsClientRegistered());
785 #if !defined(OS_ANDROID)
786 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
789 // Kick off another policy fetch.
790 MockDeviceManagementJob* fetch_request = NULL;
791 EXPECT_CALL(device_management_service_,
792 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
793 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
794 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
796 manager_->RefreshPolicies();
797 Mock::VerifyAndClearExpectations(this);
799 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
800 // indicates that chrome management is disabled and will result in the cached
801 // policy being removed and the manager shut down.
802 EXPECT_CALL(*mock_store_, Clear());
803 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
804 em::DeviceManagementResponse());
805 base::RunLoop().RunUntilIdle();
806 EXPECT_FALSE(manager_->IsClientRegistered());
807 #if !defined(OS_ANDROID)
808 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
814 } // namespace policy