Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
bloba1cfd8c40606946be24c791a9f7ca43b29639519
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/memory/scoped_ptr.h"
7 #include "base/prefs/pref_service.h"
8 #include "base/run_loop.h"
9 #include "base/thread_task_runner_handle.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/account_fetcher_service_factory.h"
18 #include "chrome/browser/signin/chrome_signin_client_factory.h"
19 #include "chrome/browser/signin/fake_account_fetcher_service.h"
20 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
21 #include "chrome/browser/signin/fake_signin_manager_builder.h"
22 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
23 #include "chrome/browser/signin/signin_manager_factory.h"
24 #include "chrome/browser/signin/test_signin_client_builder.h"
25 #include "chrome/test/base/testing_browser_process.h"
26 #include "chrome/test/base/testing_pref_service_syncable.h"
27 #include "chrome/test/base/testing_profile.h"
28 #include "components/policy/core/browser/browser_policy_connector.h"
29 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
30 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
31 #include "components/policy/core/common/cloud/mock_device_management_service.h"
32 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
33 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
34 #include "components/policy/core/common/schema_registry.h"
35 #include "components/signin/core/browser/account_tracker_service.h"
36 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
37 #include "components/signin/core/browser/signin_manager.h"
38 #include "content/public/browser/browser_context.h"
39 #include "content/public/browser/notification_details.h"
40 #include "content/public/browser/notification_service.h"
41 #include "content/public/browser/notification_source.h"
42 #include "content/public/test/test_browser_thread_bundle.h"
43 #include "google_apis/gaia/gaia_constants.h"
44 #include "google_apis/gaia/google_service_auth_error.h"
45 #include "net/http/http_status_code.h"
46 #include "net/url_request/test_url_fetcher_factory.h"
47 #include "net/url_request/url_request_context_getter.h"
48 #include "net/url_request/url_request_status.h"
49 #include "net/url_request/url_request_test_util.h"
50 #include "testing/gmock/include/gmock/gmock.h"
51 #include "testing/gtest/include/gtest/gtest.h"
53 #if defined(OS_ANDROID)
54 #include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
55 #else
56 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
57 #endif
59 namespace em = enterprise_management;
61 using testing::AnyNumber;
62 using testing::Mock;
63 using testing::_;
65 namespace policy {
67 namespace {
69 const char kTestGaiaId[] = "gaia-id-testuser@test.com";
70 const char kTestUser[] = "testuser@test.com";
72 #if !defined(OS_ANDROID)
73 const char kValidTokenResponse[] =
74 "{"
75 " \"access_token\": \"at1\","
76 " \"expires_in\": 3600,"
77 " \"token_type\": \"Bearer\""
78 "}";
79 #endif
81 const char kHostedDomainResponse[] =
82 "{"
83 " \"hd\": \"test.com\""
84 "}";
86 UserCloudPolicyManager* BuildCloudPolicyManager(
87 content::BrowserContext* context) {
88 MockUserCloudPolicyStore* store = new MockUserCloudPolicyStore();
89 EXPECT_CALL(*store, Load()).Times(AnyNumber());
91 return new UserCloudPolicyManager(
92 scoped_ptr<UserCloudPolicyStore>(store),
93 base::FilePath(),
94 scoped_ptr<CloudExternalDataManager>(),
95 base::ThreadTaskRunnerHandle::Get(),
96 base::ThreadTaskRunnerHandle::Get(),
97 base::ThreadTaskRunnerHandle::Get());
100 class UserPolicySigninServiceTest : public testing::Test {
101 public:
102 UserPolicySigninServiceTest()
103 : mock_store_(NULL),
104 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
105 register_completed_(false) {}
107 MOCK_METHOD1(OnPolicyRefresh, void(bool));
109 void OnRegisterCompleted(const std::string& dm_token,
110 const std::string& client_id) {
111 register_completed_ = true;
112 dm_token_ = dm_token;
113 client_id_ = client_id;
116 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
117 // Policy client registration on Android depends on Token Service having
118 // a valid login token, while on other platforms, the login refresh token
119 // is specified directly.
120 #if defined(OS_ANDROID)
121 GetTokenService()->UpdateCredentials(
122 AccountTrackerService::PickAccountIdForAccount(
123 profile_.get()->GetPrefs(), kTestGaiaId, kTestUser),
124 "oauth2_login_refresh_token");
125 #endif
126 service->RegisterForPolicy(
127 kTestUser,
128 #if !defined(OS_ANDROID)
129 "mock_oauth_token",
130 #endif
131 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
132 base::Unretained(this)));
133 ASSERT_TRUE(IsRequestActive());
136 void SetUp() override {
137 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
138 &device_management_service_);
140 local_state_.reset(new TestingPrefServiceSimple);
141 chrome::RegisterLocalState(local_state_->registry());
142 system_request_context_getter_ = new net::TestURLRequestContextGetter(
143 base::ThreadTaskRunnerHandle::Get());
144 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
145 system_request_context_getter_.get());
146 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
148 g_browser_process->browser_policy_connector()->Init(
149 local_state_.get(), system_request_context_getter_);
151 // Create a testing profile with cloud-policy-on-signin enabled, and bring
152 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
153 scoped_ptr<TestingPrefServiceSyncable> prefs(
154 new TestingPrefServiceSyncable());
155 chrome::RegisterUserProfilePrefs(prefs->registry());
157 // UserCloudPolicyManagerFactory isn't a real
158 // BrowserContextKeyedServiceFactory (it derives from
159 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
160 // instances) so we have to inject our testing factory via a special
161 // API before creating the profile.
162 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
163 BuildCloudPolicyManager);
164 TestingProfile::Builder builder;
165 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
166 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
167 BuildFakeSigninManagerBase);
168 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
169 BuildFakeProfileOAuth2TokenService);
170 builder.AddTestingFactory(AccountFetcherServiceFactory::GetInstance(),
171 FakeAccountFetcherService::BuildForTests);
172 builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(),
173 signin::BuildTestSigninClient);
175 profile_ = builder.Build().Pass();
176 url_factory_.set_remove_fetcher_on_delete(true);
178 signin_manager_ = static_cast<FakeSigninManager*>(
179 SigninManagerFactory::GetForProfile(profile_.get()));
180 // Tests are responsible for freeing the UserCloudPolicyManager instances
181 // they inject.
182 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
183 profile_.get()));
184 manager_->Init(&schema_registry_);
185 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
186 manager_->core()->store());
187 DCHECK(mock_store_);
188 AddProfile();
190 Mock::VerifyAndClearExpectations(mock_store_);
193 void TearDown() override {
194 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
195 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
196 // Free the profile before we clear out the browser prefs.
197 profile_.reset();
198 TestingBrowserProcess* testing_browser_process =
199 TestingBrowserProcess::GetGlobal();
200 testing_browser_process->SetLocalState(NULL);
201 local_state_.reset();
202 testing_browser_process->SetBrowserPolicyConnector(NULL);
203 base::RunLoop run_loop;
204 run_loop.RunUntilIdle();
207 virtual void AddProfile() {
208 // For this test, the user should not be signed in yet.
209 DCHECK(!signin_manager_->IsAuthenticated());
211 // Initializing UserPolicySigninService while the user is not signed in
212 // should result in the store being cleared to remove any lingering policy.
213 EXPECT_CALL(*mock_store_, Clear());
215 // Let the SigninService know that the profile has been created.
216 content::NotificationService::current()->Notify(
217 chrome::NOTIFICATION_PROFILE_ADDED,
218 content::Source<Profile>(profile_.get()),
219 content::NotificationService::NoDetails());
222 FakeProfileOAuth2TokenService* GetTokenService() {
223 ProfileOAuth2TokenService* service =
224 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
225 return static_cast<FakeProfileOAuth2TokenService*>(service);
228 bool IsRequestActive() {
229 if (!GetTokenService()->GetPendingRequests().empty())
230 return true;
231 return url_factory_.GetFetcherByID(0);
234 void MakeOAuthTokenFetchSucceed() {
235 ASSERT_TRUE(IsRequestActive());
236 #if defined(OS_ANDROID)
237 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
238 base::Time::Now());
239 #else
240 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
241 fetcher->set_response_code(net::HTTP_OK);
242 fetcher->SetResponseString(kValidTokenResponse);
243 fetcher->delegate()->OnURLFetchComplete(fetcher);
244 #endif
247 void ReportHostedDomainStatus(bool is_hosted_domain) {
248 ASSERT_TRUE(IsRequestActive());
249 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
250 fetcher->set_response_code(net::HTTP_OK);
251 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
252 fetcher->delegate()->OnURLFetchComplete(fetcher);
255 void TestSuccessfulSignin() {
256 UserPolicySigninService* signin_service =
257 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
258 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
259 RegisterPolicyClientWithCallback(signin_service);
261 // Mimic successful oauth token fetch.
262 MakeOAuthTokenFetchSucceed();
264 // When the user is from a hosted domain, this should kick off client
265 // registration.
266 MockDeviceManagementJob* register_request = NULL;
267 EXPECT_CALL(device_management_service_,
268 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
269 .WillOnce(device_management_service_.CreateAsyncJob(
270 &register_request));
271 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
272 .Times(1);
274 // Now mimic the user being a hosted domain - this should cause a Register()
275 // call.
276 ReportHostedDomainStatus(true);
278 // Should have no more outstanding requests.
279 ASSERT_FALSE(IsRequestActive());
280 Mock::VerifyAndClearExpectations(this);
281 ASSERT_TRUE(register_request);
283 // Mimic successful client registration - this should register the client
284 // and invoke the callback.
285 em::DeviceManagementResponse registration_blob;
286 std::string expected_dm_token = "dm_token";
287 registration_blob.mutable_register_response()->set_device_management_token(
288 expected_dm_token);
289 registration_blob.mutable_register_response()->set_enrollment_type(
290 em::DeviceRegisterResponse::ENTERPRISE);
291 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
293 // UserCloudPolicyManager should not be initialized yet.
294 ASSERT_FALSE(manager_->core()->service());
295 EXPECT_TRUE(register_completed_);
296 EXPECT_EQ(dm_token_, expected_dm_token);
298 // Now call to fetch policy - this should fire off a fetch request.
299 MockDeviceManagementJob* fetch_request = NULL;
300 EXPECT_CALL(device_management_service_,
301 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
302 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
303 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
304 .Times(1);
306 signin_service->FetchPolicyForSignedInUser(
307 kTestUser,
308 dm_token_,
309 client_id_,
310 profile_->GetRequestContext(),
311 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
312 base::Unretained(this)));
314 Mock::VerifyAndClearExpectations(this);
315 ASSERT_TRUE(fetch_request);
317 // UserCloudPolicyManager should now be initialized.
318 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
319 ASSERT_TRUE(manager_->core()->service());
321 // Make the policy fetch succeed - this should result in a write to the
322 // store and ultimately result in a call to OnPolicyRefresh().
323 EXPECT_CALL(*mock_store_, Store(_));
324 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
326 // Create a fake policy blob to deliver to the client.
327 em::DeviceManagementResponse policy_blob;
328 em::PolicyData policy_data;
329 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
330 em::PolicyFetchResponse* policy_response =
331 policy_blob.mutable_policy_response()->add_response();
332 ASSERT_TRUE(policy_data.SerializeToString(
333 policy_response->mutable_policy_data()));
334 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
336 // Complete the store which should cause the policy fetch callback to be
337 // invoked.
338 mock_store_->NotifyStoreLoaded();
339 Mock::VerifyAndClearExpectations(this);
342 scoped_ptr<TestingProfile> profile_;
343 MockUserCloudPolicyStore* mock_store_; // Not owned.
344 SchemaRegistry schema_registry_;
345 scoped_ptr<UserCloudPolicyManager> manager_;
347 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
348 // various components asynchronously via tasks, so create fake threads here.
349 content::TestBrowserThreadBundle thread_bundle_;
351 net::TestURLFetcherFactory url_factory_;
353 FakeSigninManager* signin_manager_;
355 // Used in conjunction with OnRegisterCompleted() to test client registration
356 // callbacks.
357 std::string dm_token_;
358 std::string client_id_;
360 // True if OnRegisterCompleted() was called.
361 bool register_completed_;
363 // Weak ptr to the MockDeviceManagementService (object is owned by the
364 // BrowserPolicyConnector).
365 MockDeviceManagementService device_management_service_;
367 scoped_ptr<TestingPrefServiceSimple> local_state_;
368 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
371 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
372 public:
373 void AddProfile() override {
374 // UserCloudPolicyManager should not be initialized.
375 ASSERT_FALSE(manager_->core()->service());
377 // Set the user as signed in.
378 SigninManagerFactory::GetForProfile(profile_.get())->
379 SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
381 // Let the SigninService know that the profile has been created.
382 content::NotificationService::current()->Notify(
383 chrome::NOTIFICATION_PROFILE_ADDED,
384 content::Source<Profile>(profile_.get()),
385 content::NotificationService::NoDetails());
389 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
390 // Make sure user is not signed in.
391 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
392 IsAuthenticated());
394 // UserCloudPolicyManager should not be initialized.
395 ASSERT_FALSE(manager_->core()->service());
398 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
399 // token after signin. Revisit this after figuring how to handle that on
400 // Android.
401 #if !defined(OS_ANDROID)
403 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
404 // UserCloudPolicyManager should be initialized.
405 ASSERT_TRUE(manager_->core()->service());
407 // Complete initialization of the store.
408 mock_store_->NotifyStoreLoaded();
410 // No oauth access token yet, so client registration should be deferred.
411 ASSERT_FALSE(IsRequestActive());
413 // Make oauth token available.
414 GetTokenService()->UpdateCredentials(
415 SigninManagerFactory::GetForProfile(profile_.get())
416 ->GetAuthenticatedAccountId(),
417 "oauth_login_refresh_token");
419 // Client registration should be in progress since we now have an oauth token.
420 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
421 ASSERT_TRUE(IsRequestActive());
424 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
425 // UserCloudPolicyManager should be initialized.
426 ASSERT_TRUE(manager_->core()->service());
428 // Complete initialization of the store.
429 mock_store_->NotifyStoreLoaded();
431 // No oauth access token yet, so client registration should be deferred.
432 ASSERT_FALSE(IsRequestActive());
434 // Make oauth token available.
435 GetTokenService()->UpdateCredentials(
436 SigninManagerFactory::GetForProfile(profile_.get())
437 ->GetAuthenticatedAccountId(),
438 "oauth_login_refresh_token");
440 // Client registration should be in progress since we now have an oauth token.
441 ASSERT_TRUE(IsRequestActive());
443 // Now fail the access token fetch.
444 GoogleServiceAuthError error(
445 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
446 GetTokenService()->IssueErrorForAllPendingRequests(error);
447 ASSERT_FALSE(IsRequestActive());
450 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
451 // UserCloudPolicyManager should not be initialized since there is no
452 // signed-in user.
453 ASSERT_FALSE(manager_->core()->service());
455 // Now sign in the user.
456 SigninManagerFactory::GetForProfile(profile_.get())
457 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
459 // Complete initialization of the store.
460 mock_store_->NotifyStoreLoaded();
462 // Make oauth token available.
463 GetTokenService()->UpdateCredentials(
464 SigninManagerFactory::GetForProfile(profile_.get())
465 ->GetAuthenticatedAccountId(),
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
478 // signed-in user.
479 ASSERT_FALSE(manager_->core()->service());
481 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
482 SigninManagerFactory::GetForProfile(profile_.get())
483 ->SetAuthenticatedAccountInfo("gaia-id-non_enterprise_user@gmail.com",
484 "non_enterprise_user@gmail.com");
486 // Complete initialization of the store.
487 mock_store_->NotifyStoreLoaded();
489 // Make oauth token available.
490 GetTokenService()->UpdateCredentials(
491 SigninManagerFactory::GetForProfile(profile_.get())
492 ->GetAuthenticatedAccountId(),
493 "oauth_login_refresh_token");
495 // UserCloudPolicyManager should not be initialized and there should be no
496 // DMToken request active.
497 ASSERT_TRUE(!manager_->core()->service());
498 ASSERT_FALSE(IsRequestActive());
501 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
502 // UserCloudPolicyManager should not be initialized since there is no
503 // signed-in user.
504 ASSERT_FALSE(manager_->core()->service());
506 // Now sign in the user.
507 SigninManagerFactory::GetForProfile(profile_.get())
508 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
510 // Make oauth token available.
511 GetTokenService()->UpdateCredentials(
512 SigninManagerFactory::GetForProfile(profile_.get())
513 ->GetAuthenticatedAccountId(),
514 "oauth_login_refresh_token");
516 // UserCloudPolicyManager should be initialized.
517 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
518 ASSERT_TRUE(manager_->core()->service());
520 // Client registration should not be in progress since the store is not
521 // yet initialized.
522 ASSERT_FALSE(IsRequestActive());
524 // Complete initialization of the store with no policy (unregistered client).
525 mock_store_->NotifyStoreLoaded();
527 // Client registration should be in progress since we have an oauth token.
528 ASSERT_TRUE(IsRequestActive());
531 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
532 // UserCloudPolicyManager should not be initialized since there is no
533 // signed-in user.
534 ASSERT_FALSE(manager_->core()->service());
536 // Now sign in the user.
537 SigninManagerFactory::GetForProfile(profile_.get())
538 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
540 // Make oauth token available.
541 GetTokenService()->UpdateCredentials(
542 SigninManagerFactory::GetForProfile(profile_.get())
543 ->GetAuthenticatedAccountId(),
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
551 // yet initialized.
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());
578 // Now sign out.
579 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
580 signin_metrics::SIGNOUT_TEST);
582 // UserCloudPolicyManager should be shut down.
583 ASSERT_FALSE(manager_->core()->service());
586 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
587 UserPolicySigninService* signin_service =
588 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
589 RegisterPolicyClientWithCallback(signin_service);
590 Mock::VerifyAndClearExpectations(this);
592 // UserCloudPolicyManager should not be initialized.
593 ASSERT_FALSE(manager_->core()->service());
594 ASSERT_TRUE(IsRequestActive());
595 EXPECT_FALSE(register_completed_);
597 // Cause the access token fetch to fail - callback should be invoked.
598 #if defined(OS_ANDROID)
599 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
600 GetTokenService()->IssueErrorForAllPendingRequests(
601 GoogleServiceAuthError::FromServiceError("fail"));
602 #else
603 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
604 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
605 fetcher->delegate()->OnURLFetchComplete(fetcher);
606 #endif
608 EXPECT_TRUE(register_completed_);
609 EXPECT_TRUE(dm_token_.empty());
610 EXPECT_FALSE(IsRequestActive());
613 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
614 UserPolicySigninService* signin_service =
615 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
616 RegisterPolicyClientWithCallback(signin_service);
618 // UserCloudPolicyManager should not be initialized.
619 ASSERT_FALSE(manager_->core()->service());
620 ASSERT_TRUE(IsRequestActive());
622 // Cause the access token request to succeed.
623 MakeOAuthTokenFetchSucceed();
625 // Should be a follow-up fetch to check the hosted-domain status.
626 ASSERT_TRUE(IsRequestActive());
627 Mock::VerifyAndClearExpectations(this);
629 EXPECT_FALSE(register_completed_);
631 // Report that the user is not on a hosted domain - callback should be
632 // invoked reporting a failed fetch.
633 ReportHostedDomainStatus(false);
635 // Since this is not a hosted domain, we should not issue a request for a
636 // DMToken.
637 EXPECT_TRUE(register_completed_);
638 EXPECT_TRUE(dm_token_.empty());
639 ASSERT_FALSE(IsRequestActive());
642 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
643 UserPolicySigninService* signin_service =
644 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
645 RegisterPolicyClientWithCallback(signin_service);
647 // UserCloudPolicyManager should not be initialized.
648 ASSERT_FALSE(manager_->core()->service());
650 // Mimic successful oauth token fetch.
651 MakeOAuthTokenFetchSucceed();
653 EXPECT_FALSE(register_completed_);
655 // When the user is from a hosted domain, this should kick off client
656 // registration.
657 MockDeviceManagementJob* register_request = NULL;
658 EXPECT_CALL(device_management_service_,
659 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
660 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
661 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
662 .Times(1);
664 // Now mimic the user being a hosted domain - this should cause a Register()
665 // call.
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 // Make client registration fail (hosted domain user that is not managed).
675 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
676 em::DeviceManagementResponse());
677 EXPECT_TRUE(register_completed_);
678 EXPECT_TRUE(dm_token_.empty());
681 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
682 UserPolicySigninService* signin_service =
683 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
684 RegisterPolicyClientWithCallback(signin_service);
686 // Mimic successful oauth token fetch.
687 MakeOAuthTokenFetchSucceed();
689 // When the user is from a hosted domain, this should kick off client
690 // registration.
691 MockDeviceManagementJob* register_request = NULL;
692 EXPECT_CALL(device_management_service_,
693 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
694 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
695 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
696 .Times(1);
698 // Now mimic the user being a hosted domain - this should cause a Register()
699 // call.
700 ReportHostedDomainStatus(true);
702 // Should have no more outstanding requests.
703 ASSERT_FALSE(IsRequestActive());
704 Mock::VerifyAndClearExpectations(this);
705 ASSERT_TRUE(register_request);
706 EXPECT_FALSE(register_completed_);
708 em::DeviceManagementResponse registration_blob;
709 std::string expected_dm_token = "dm_token";
710 registration_blob.mutable_register_response()->set_device_management_token(
711 expected_dm_token);
712 registration_blob.mutable_register_response()->set_enrollment_type(
713 em::DeviceRegisterResponse::ENTERPRISE);
714 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
715 Mock::VerifyAndClearExpectations(this);
716 EXPECT_TRUE(register_completed_);
717 EXPECT_EQ(dm_token_, expected_dm_token);
718 // UserCloudPolicyManager should not be initialized.
719 ASSERT_FALSE(manager_->core()->service());
722 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
723 // Initiate a policy fetch request.
724 MockDeviceManagementJob* fetch_request = NULL;
725 EXPECT_CALL(device_management_service_,
726 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
727 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
728 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
729 .Times(1);
730 UserPolicySigninService* signin_service =
731 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
732 signin_service->FetchPolicyForSignedInUser(
733 kTestUser,
734 "mock_dm_token",
735 "mock_client_id",
736 profile_->GetRequestContext(),
737 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
738 base::Unretained(this)));
739 ASSERT_TRUE(fetch_request);
741 // Make the policy fetch fail.
742 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
743 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
744 em::DeviceManagementResponse());
746 // UserCloudPolicyManager should be initialized.
747 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
748 ASSERT_TRUE(manager_->core()->service());
751 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
752 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
755 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
756 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
758 EXPECT_CALL(*mock_store_, Clear());
759 signin_manager_->ForceSignOut();
760 ASSERT_FALSE(manager_->core()->service());
762 // Now sign in again.
763 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
766 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
767 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
769 ASSERT_TRUE(manager_->IsClientRegistered());
771 // Kick off another policy fetch.
772 MockDeviceManagementJob* fetch_request = NULL;
773 EXPECT_CALL(device_management_service_,
774 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
775 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
776 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
777 .Times(1);
778 manager_->RefreshPolicies();
779 Mock::VerifyAndClearExpectations(this);
781 // Now, fake a transient error from the server on this policy fetch. This
782 // should have no impact on the cached policy.
783 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
784 em::DeviceManagementResponse());
785 base::RunLoop().RunUntilIdle();
786 ASSERT_TRUE(manager_->IsClientRegistered());
789 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
790 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
792 EXPECT_TRUE(manager_->IsClientRegistered());
793 #if !defined(OS_ANDROID)
794 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
795 #endif
797 // Kick off another policy fetch.
798 MockDeviceManagementJob* fetch_request = NULL;
799 EXPECT_CALL(device_management_service_,
800 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
801 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
802 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
803 .Times(1);
804 manager_->RefreshPolicies();
805 Mock::VerifyAndClearExpectations(this);
807 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
808 // indicates that chrome management is disabled and will result in the cached
809 // policy being removed and the manager shut down.
810 EXPECT_CALL(*mock_store_, Clear());
811 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
812 em::DeviceManagementResponse());
813 base::RunLoop().RunUntilIdle();
814 EXPECT_FALSE(manager_->IsClientRegistered());
815 #if !defined(OS_ANDROID)
816 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
817 #endif
820 } // namespace
822 } // namespace policy