Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
blob9bd390857d68ad98a1925e764dbeb9a7bf0c045f
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/account_tracker_service_factory.h"
18 #include "chrome/browser/signin/chrome_signin_client_factory.h"
19 #include "chrome/browser/signin/fake_account_tracker_service.h"
20 #include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
21 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
22 #include "chrome/browser/signin/fake_signin_manager.h"
23 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
24 #include "chrome/browser/signin/signin_manager_factory.h"
25 #include "chrome/browser/signin/test_signin_client_builder.h"
26 #include "chrome/test/base/testing_browser_process.h"
27 #include "chrome/test/base/testing_pref_service_syncable.h"
28 #include "chrome/test/base/testing_profile.h"
29 #include "components/policy/core/browser/browser_policy_connector.h"
30 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
31 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
32 #include "components/policy/core/common/cloud/mock_device_management_service.h"
33 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
34 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
35 #include "components/policy/core/common/schema_registry.h"
36 #include "components/signin/core/browser/signin_manager.h"
37 #include "content/public/browser/browser_context.h"
38 #include "content/public/browser/notification_details.h"
39 #include "content/public/browser/notification_service.h"
40 #include "content/public/browser/notification_source.h"
41 #include "content/public/test/test_browser_thread_bundle.h"
42 #include "google_apis/gaia/gaia_constants.h"
43 #include "google_apis/gaia/google_service_auth_error.h"
44 #include "net/http/http_status_code.h"
45 #include "net/url_request/test_url_fetcher_factory.h"
46 #include "net/url_request/url_request_context_getter.h"
47 #include "net/url_request/url_request_status.h"
48 #include "net/url_request/url_request_test_util.h"
49 #include "testing/gmock/include/gmock/gmock.h"
50 #include "testing/gtest/include/gtest/gtest.h"
52 #if defined(OS_ANDROID)
53 #include "chrome/browser/policy/cloud/user_policy_signin_service_mobile.h"
54 #else
55 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
56 #endif
58 namespace em = enterprise_management;
60 using testing::AnyNumber;
61 using testing::Mock;
62 using testing::_;
64 namespace policy {
66 namespace {
68 const char kTestUser[] = "testuser@test.com";
70 #if !defined(OS_ANDROID)
71 const char kValidTokenResponse[] =
72 "{"
73 " \"access_token\": \"at1\","
74 " \"expires_in\": 3600,"
75 " \"token_type\": \"Bearer\""
76 "}";
77 #endif
79 const char kHostedDomainResponse[] =
80 "{"
81 " \"hd\": \"test.com\""
82 "}";
84 class SigninManagerFake : public FakeSigninManager {
85 public:
86 explicit SigninManagerFake(Profile* profile)
87 : FakeSigninManager(profile) {
88 Initialize(NULL);
91 void ForceSignOut() {
92 // Allow signing out now.
93 prohibit_signout_ = false;
94 SignOut(signin_metrics::SIGNOUT_TEST);
97 static KeyedService* Build(content::BrowserContext* profile) {
98 return new SigninManagerFake(static_cast<Profile*>(profile));
102 UserCloudPolicyManager* BuildCloudPolicyManager(
103 content::BrowserContext* context) {
104 MockUserCloudPolicyStore* store = new MockUserCloudPolicyStore();
105 EXPECT_CALL(*store, Load()).Times(AnyNumber());
107 return new UserCloudPolicyManager(
108 scoped_ptr<UserCloudPolicyStore>(store),
109 base::FilePath(),
110 scoped_ptr<CloudExternalDataManager>(),
111 base::MessageLoopProxy::current(),
112 base::MessageLoopProxy::current(),
113 base::MessageLoopProxy::current());
116 class UserPolicySigninServiceTest : public testing::Test {
117 public:
118 UserPolicySigninServiceTest()
119 : mock_store_(NULL),
120 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
121 register_completed_(false) {}
123 MOCK_METHOD1(OnPolicyRefresh, void(bool));
125 void OnRegisterCompleted(const std::string& dm_token,
126 const std::string& client_id) {
127 register_completed_ = true;
128 dm_token_ = dm_token;
129 client_id_ = client_id;
132 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
133 // Policy client registration on Android depends on Token Service having
134 // a valid login token, while on other platforms, the login refresh token
135 // is specified directly.
136 #if defined(OS_ANDROID)
137 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
138 "oauth2_login_refresh_token");
139 #endif
140 service->RegisterForPolicy(
141 kTestUser,
142 #if !defined(OS_ANDROID)
143 "mock_oauth_token",
144 #endif
145 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
146 base::Unretained(this)));
147 ASSERT_TRUE(IsRequestActive());
150 virtual void SetUp() override {
151 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
152 &device_management_service_);
154 local_state_.reset(new TestingPrefServiceSimple);
155 chrome::RegisterLocalState(local_state_->registry());
156 system_request_context_getter_ = new net::TestURLRequestContextGetter(
157 base::MessageLoopProxy::current());
158 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
159 system_request_context_getter_.get());
160 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
162 g_browser_process->browser_policy_connector()->Init(
163 local_state_.get(), system_request_context_getter_);
165 // Create a testing profile with cloud-policy-on-signin enabled, and bring
166 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
167 scoped_ptr<TestingPrefServiceSyncable> prefs(
168 new TestingPrefServiceSyncable());
169 chrome::RegisterUserProfilePrefs(prefs->registry());
171 // UserCloudPolicyManagerFactory isn't a real
172 // BrowserContextKeyedServiceFactory (it derives from
173 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
174 // instances) so we have to inject our testing factory via a special
175 // API before creating the profile.
176 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
177 BuildCloudPolicyManager);
178 TestingProfile::Builder builder;
179 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
180 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
181 SigninManagerFake::Build);
182 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
183 BuildFakeProfileOAuth2TokenService);
184 builder.AddTestingFactory(AccountTrackerServiceFactory::GetInstance(),
185 FakeAccountTrackerService::Build);
186 builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(),
187 signin::BuildTestSigninClient);
189 profile_ = builder.Build().Pass();
190 url_factory_.set_remove_fetcher_on_delete(true);
192 signin_manager_ = static_cast<SigninManagerFake*>(
193 SigninManagerFactory::GetForProfile(profile_.get()));
194 // Tests are responsible for freeing the UserCloudPolicyManager instances
195 // they inject.
196 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
197 profile_.get()));
198 manager_->Init(&schema_registry_);
199 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
200 manager_->core()->store());
201 DCHECK(mock_store_);
202 AddProfile();
204 Mock::VerifyAndClearExpectations(mock_store_);
207 virtual void TearDown() override {
208 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
209 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
210 // Free the profile before we clear out the browser prefs.
211 profile_.reset();
212 TestingBrowserProcess* testing_browser_process =
213 TestingBrowserProcess::GetGlobal();
214 testing_browser_process->SetLocalState(NULL);
215 local_state_.reset();
216 testing_browser_process->SetBrowserPolicyConnector(NULL);
217 base::RunLoop run_loop;
218 run_loop.RunUntilIdle();
221 virtual void AddProfile() {
222 // For this test, the user should not be signed in yet.
223 DCHECK(!signin_manager_->IsAuthenticated());
225 // Initializing UserPolicySigninService while the user is not signed in
226 // should result in the store being cleared to remove any lingering policy.
227 EXPECT_CALL(*mock_store_, Clear());
229 // Let the SigninService know that the profile has been created.
230 content::NotificationService::current()->Notify(
231 chrome::NOTIFICATION_PROFILE_ADDED,
232 content::Source<Profile>(profile_.get()),
233 content::NotificationService::NoDetails());
236 FakeProfileOAuth2TokenService* GetTokenService() {
237 ProfileOAuth2TokenService* service =
238 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
239 return static_cast<FakeProfileOAuth2TokenService*>(service);
242 bool IsRequestActive() {
243 if (!GetTokenService()->GetPendingRequests().empty())
244 return true;
245 return url_factory_.GetFetcherByID(0);
248 void MakeOAuthTokenFetchSucceed() {
249 ASSERT_TRUE(IsRequestActive());
250 #if defined(OS_ANDROID)
251 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
252 base::Time::Now());
253 #else
254 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
255 fetcher->set_response_code(net::HTTP_OK);
256 fetcher->SetResponseString(kValidTokenResponse);
257 fetcher->delegate()->OnURLFetchComplete(fetcher);
258 #endif
261 void ReportHostedDomainStatus(bool is_hosted_domain) {
262 ASSERT_TRUE(IsRequestActive());
263 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
264 fetcher->set_response_code(net::HTTP_OK);
265 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
266 fetcher->delegate()->OnURLFetchComplete(fetcher);
269 void TestSuccessfulSignin() {
270 UserPolicySigninService* signin_service =
271 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
272 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
273 RegisterPolicyClientWithCallback(signin_service);
275 // Mimic successful oauth token fetch.
276 MakeOAuthTokenFetchSucceed();
278 // When the user is from a hosted domain, this should kick off client
279 // registration.
280 MockDeviceManagementJob* register_request = NULL;
281 EXPECT_CALL(device_management_service_,
282 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
283 .WillOnce(device_management_service_.CreateAsyncJob(
284 &register_request));
285 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
286 .Times(1);
288 // Now mimic the user being a hosted domain - this should cause a Register()
289 // call.
290 ReportHostedDomainStatus(true);
292 // Should have no more outstanding requests.
293 ASSERT_FALSE(IsRequestActive());
294 Mock::VerifyAndClearExpectations(this);
295 ASSERT_TRUE(register_request);
297 // Mimic successful client registration - this should register the client
298 // and invoke the callback.
299 em::DeviceManagementResponse registration_blob;
300 std::string expected_dm_token = "dm_token";
301 registration_blob.mutable_register_response()->set_device_management_token(
302 expected_dm_token);
303 registration_blob.mutable_register_response()->set_enrollment_type(
304 em::DeviceRegisterResponse::ENTERPRISE);
305 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
307 // UserCloudPolicyManager should not be initialized yet.
308 ASSERT_FALSE(manager_->core()->service());
309 EXPECT_TRUE(register_completed_);
310 EXPECT_EQ(dm_token_, expected_dm_token);
312 // Now call to fetch policy - this should fire off a fetch request.
313 MockDeviceManagementJob* fetch_request = NULL;
314 EXPECT_CALL(device_management_service_,
315 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
316 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
317 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
318 .Times(1);
320 signin_service->FetchPolicyForSignedInUser(
321 kTestUser,
322 dm_token_,
323 client_id_,
324 profile_->GetRequestContext(),
325 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
326 base::Unretained(this)));
328 Mock::VerifyAndClearExpectations(this);
329 ASSERT_TRUE(fetch_request);
331 // UserCloudPolicyManager should now be initialized.
332 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
333 ASSERT_TRUE(manager_->core()->service());
335 // Make the policy fetch succeed - this should result in a write to the
336 // store and ultimately result in a call to OnPolicyRefresh().
337 EXPECT_CALL(*mock_store_, Store(_));
338 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
340 // Create a fake policy blob to deliver to the client.
341 em::DeviceManagementResponse policy_blob;
342 em::PolicyData policy_data;
343 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
344 em::PolicyFetchResponse* policy_response =
345 policy_blob.mutable_policy_response()->add_response();
346 ASSERT_TRUE(policy_data.SerializeToString(
347 policy_response->mutable_policy_data()));
348 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
350 // Complete the store which should cause the policy fetch callback to be
351 // invoked.
352 mock_store_->NotifyStoreLoaded();
353 Mock::VerifyAndClearExpectations(this);
356 scoped_ptr<TestingProfile> profile_;
357 MockUserCloudPolicyStore* mock_store_; // Not owned.
358 SchemaRegistry schema_registry_;
359 scoped_ptr<UserCloudPolicyManager> manager_;
361 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
362 // various components asynchronously via tasks, so create fake threads here.
363 content::TestBrowserThreadBundle thread_bundle_;
365 net::TestURLFetcherFactory url_factory_;
367 SigninManagerFake* signin_manager_;
369 // Used in conjunction with OnRegisterCompleted() to test client registration
370 // callbacks.
371 std::string dm_token_;
372 std::string client_id_;
374 // True if OnRegisterCompleted() was called.
375 bool register_completed_;
377 // Weak ptr to the MockDeviceManagementService (object is owned by the
378 // BrowserPolicyConnector).
379 MockDeviceManagementService device_management_service_;
381 scoped_ptr<TestingPrefServiceSimple> local_state_;
382 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
385 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
386 public:
387 void AddProfile() override {
388 // UserCloudPolicyManager should not be initialized.
389 ASSERT_FALSE(manager_->core()->service());
391 // Set the user as signed in.
392 SigninManagerFactory::GetForProfile(profile_.get())->
393 SetAuthenticatedUsername(kTestUser);
395 // Let the SigninService know that the profile has been created.
396 content::NotificationService::current()->Notify(
397 chrome::NOTIFICATION_PROFILE_ADDED,
398 content::Source<Profile>(profile_.get()),
399 content::NotificationService::NoDetails());
403 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
404 // Make sure user is not signed in.
405 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
406 IsAuthenticated());
408 // UserCloudPolicyManager should not be initialized.
409 ASSERT_FALSE(manager_->core()->service());
412 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
413 // token after signin. Revisit this after figuring how to handle that on
414 // Android.
415 #if !defined(OS_ANDROID)
417 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
418 // UserCloudPolicyManager should be initialized.
419 ASSERT_TRUE(manager_->core()->service());
421 // Complete initialization of the store.
422 mock_store_->NotifyStoreLoaded();
424 // No oauth access token yet, so client registration should be deferred.
425 ASSERT_FALSE(IsRequestActive());
427 // Make oauth token available.
428 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
429 "oauth_login_refresh_token");
431 // Client registration should be in progress since we now have an oauth token.
432 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
433 ASSERT_TRUE(IsRequestActive());
436 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
437 // UserCloudPolicyManager should be initialized.
438 ASSERT_TRUE(manager_->core()->service());
440 // Complete initialization of the store.
441 mock_store_->NotifyStoreLoaded();
443 // No oauth access token yet, so client registration should be deferred.
444 ASSERT_FALSE(IsRequestActive());
446 // Make oauth token available.
447 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
448 "oauth_login_refresh_token");
450 // Client registration should be in progress since we now have an oauth token.
451 ASSERT_TRUE(IsRequestActive());
453 // Now fail the access token fetch.
454 GoogleServiceAuthError error(
455 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
456 GetTokenService()->IssueErrorForAllPendingRequests(error);
457 ASSERT_FALSE(IsRequestActive());
460 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
461 // UserCloudPolicyManager should not be initialized since there is no
462 // signed-in user.
463 ASSERT_FALSE(manager_->core()->service());
465 // Now sign in the user.
466 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
467 kTestUser);
469 // Complete initialization of the store.
470 mock_store_->NotifyStoreLoaded();
472 // Make oauth token available.
473 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
474 "oauth_login_refresh_token");
476 // UserCloudPolicyManager should be initialized.
477 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
478 ASSERT_TRUE(manager_->core()->service());
480 // Client registration should be in progress since we have an oauth token.
481 ASSERT_TRUE(IsRequestActive());
484 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
485 // UserCloudPolicyManager should not be initialized since there is no
486 // signed-in user.
487 ASSERT_FALSE(manager_->core()->service());
489 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
490 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
491 "non_enterprise_user@gmail.com");
493 // Complete initialization of the store.
494 mock_store_->NotifyStoreLoaded();
496 // Make oauth token available.
497 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
498 "oauth_login_refresh_token");
500 // UserCloudPolicyManager should not be initialized and there should be no
501 // DMToken request active.
502 ASSERT_TRUE(!manager_->core()->service());
503 ASSERT_FALSE(IsRequestActive());
506 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
507 // UserCloudPolicyManager should not be initialized since there is no
508 // signed-in user.
509 ASSERT_FALSE(manager_->core()->service());
511 // Now sign in the user.
512 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
513 kTestUser);
515 // Make oauth token available.
516 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
517 "oauth_login_refresh_token");
519 // UserCloudPolicyManager should be initialized.
520 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
521 ASSERT_TRUE(manager_->core()->service());
523 // Client registration should not be in progress since the store is not
524 // yet initialized.
525 ASSERT_FALSE(IsRequestActive());
527 // Complete initialization of the store with no policy (unregistered client).
528 mock_store_->NotifyStoreLoaded();
530 // Client registration should be in progress since we have an oauth token.
531 ASSERT_TRUE(IsRequestActive());
534 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
535 // UserCloudPolicyManager should not be initialized since there is no
536 // signed-in user.
537 ASSERT_FALSE(manager_->core()->service());
539 // Now sign in the user.
540 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
541 kTestUser);
543 // Make oauth token available.
544 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
545 "oauth_login_refresh_token");
547 // UserCloudPolicyManager should be initialized.
548 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
549 ASSERT_TRUE(manager_->core()->service());
551 // Client registration should not be in progress since the store is not
552 // yet initialized.
553 ASSERT_FALSE(manager_->IsClientRegistered());
554 ASSERT_FALSE(IsRequestActive());
556 mock_store_->policy_.reset(new enterprise_management::PolicyData());
557 mock_store_->policy_->set_request_token("fake token");
558 mock_store_->policy_->set_device_id("fake client id");
560 // Complete initialization of the store.
561 mock_store_->NotifyStoreLoaded();
563 // Client registration should not be in progress since the client should be
564 // already registered.
565 ASSERT_TRUE(manager_->IsClientRegistered());
566 ASSERT_FALSE(IsRequestActive());
569 #endif // !defined(OS_ANDROID)
571 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
572 // UserCloudPolicyManager should be initialized.
573 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
574 ASSERT_TRUE(manager_->core()->service());
576 // Signing out will clear the policy from the store.
577 EXPECT_CALL(*mock_store_, Clear());
579 // Now sign out.
580 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
581 signin_metrics::SIGNOUT_TEST);
583 // UserCloudPolicyManager should be shut down.
584 ASSERT_FALSE(manager_->core()->service());
587 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
588 UserPolicySigninService* signin_service =
589 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
590 RegisterPolicyClientWithCallback(signin_service);
591 Mock::VerifyAndClearExpectations(this);
593 // UserCloudPolicyManager should not be initialized.
594 ASSERT_FALSE(manager_->core()->service());
595 ASSERT_TRUE(IsRequestActive());
596 EXPECT_FALSE(register_completed_);
598 // Cause the access token fetch to fail - callback should be invoked.
599 #if defined(OS_ANDROID)
600 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
601 GetTokenService()->IssueErrorForAllPendingRequests(
602 GoogleServiceAuthError::FromServiceError("fail"));
603 #else
604 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
605 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
606 fetcher->delegate()->OnURLFetchComplete(fetcher);
607 #endif
609 EXPECT_TRUE(register_completed_);
610 EXPECT_TRUE(dm_token_.empty());
611 EXPECT_FALSE(IsRequestActive());
614 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
615 UserPolicySigninService* signin_service =
616 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
617 RegisterPolicyClientWithCallback(signin_service);
619 // UserCloudPolicyManager should not be initialized.
620 ASSERT_FALSE(manager_->core()->service());
621 ASSERT_TRUE(IsRequestActive());
623 // Cause the access token request to succeed.
624 MakeOAuthTokenFetchSucceed();
626 // Should be a follow-up fetch to check the hosted-domain status.
627 ASSERT_TRUE(IsRequestActive());
628 Mock::VerifyAndClearExpectations(this);
630 EXPECT_FALSE(register_completed_);
632 // Report that the user is not on a hosted domain - callback should be
633 // invoked reporting a failed fetch.
634 ReportHostedDomainStatus(false);
636 // Since this is not a hosted domain, we should not issue a request for a
637 // DMToken.
638 EXPECT_TRUE(register_completed_);
639 EXPECT_TRUE(dm_token_.empty());
640 ASSERT_FALSE(IsRequestActive());
643 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
644 UserPolicySigninService* signin_service =
645 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
646 RegisterPolicyClientWithCallback(signin_service);
648 // UserCloudPolicyManager should not be initialized.
649 ASSERT_FALSE(manager_->core()->service());
651 // Mimic successful oauth token fetch.
652 MakeOAuthTokenFetchSucceed();
654 EXPECT_FALSE(register_completed_);
656 // When the user is from a hosted domain, this should kick off client
657 // registration.
658 MockDeviceManagementJob* register_request = NULL;
659 EXPECT_CALL(device_management_service_,
660 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
661 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
662 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
663 .Times(1);
665 // Now mimic the user being a hosted domain - this should cause a Register()
666 // call.
667 ReportHostedDomainStatus(true);
669 // Should have no more outstanding requests.
670 ASSERT_FALSE(IsRequestActive());
671 Mock::VerifyAndClearExpectations(this);
672 ASSERT_TRUE(register_request);
673 EXPECT_FALSE(register_completed_);
675 // Make client registration fail (hosted domain user that is not managed).
676 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
677 em::DeviceManagementResponse());
678 EXPECT_TRUE(register_completed_);
679 EXPECT_TRUE(dm_token_.empty());
682 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
683 UserPolicySigninService* signin_service =
684 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
685 RegisterPolicyClientWithCallback(signin_service);
687 // Mimic successful oauth token fetch.
688 MakeOAuthTokenFetchSucceed();
690 // When the user is from a hosted domain, this should kick off client
691 // registration.
692 MockDeviceManagementJob* register_request = NULL;
693 EXPECT_CALL(device_management_service_,
694 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
695 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
696 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
697 .Times(1);
699 // Now mimic the user being a hosted domain - this should cause a Register()
700 // call.
701 ReportHostedDomainStatus(true);
703 // Should have no more outstanding requests.
704 ASSERT_FALSE(IsRequestActive());
705 Mock::VerifyAndClearExpectations(this);
706 ASSERT_TRUE(register_request);
707 EXPECT_FALSE(register_completed_);
709 em::DeviceManagementResponse registration_blob;
710 std::string expected_dm_token = "dm_token";
711 registration_blob.mutable_register_response()->set_device_management_token(
712 expected_dm_token);
713 registration_blob.mutable_register_response()->set_enrollment_type(
714 em::DeviceRegisterResponse::ENTERPRISE);
715 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
716 Mock::VerifyAndClearExpectations(this);
717 EXPECT_TRUE(register_completed_);
718 EXPECT_EQ(dm_token_, expected_dm_token);
719 // UserCloudPolicyManager should not be initialized.
720 ASSERT_FALSE(manager_->core()->service());
723 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
724 // Initiate a policy fetch request.
725 MockDeviceManagementJob* fetch_request = NULL;
726 EXPECT_CALL(device_management_service_,
727 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
728 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
729 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
730 .Times(1);
731 UserPolicySigninService* signin_service =
732 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
733 signin_service->FetchPolicyForSignedInUser(
734 kTestUser,
735 "mock_dm_token",
736 "mock_client_id",
737 profile_->GetRequestContext(),
738 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
739 base::Unretained(this)));
740 ASSERT_TRUE(fetch_request);
742 // Make the policy fetch fail.
743 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
744 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
745 em::DeviceManagementResponse());
747 // UserCloudPolicyManager should be initialized.
748 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
749 ASSERT_TRUE(manager_->core()->service());
752 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
753 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
756 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
757 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
759 EXPECT_CALL(*mock_store_, Clear());
760 signin_manager_->ForceSignOut();
761 ASSERT_FALSE(manager_->core()->service());
763 // Now sign in again.
764 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
767 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
768 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
770 ASSERT_TRUE(manager_->IsClientRegistered());
772 // Kick off another policy fetch.
773 MockDeviceManagementJob* fetch_request = NULL;
774 EXPECT_CALL(device_management_service_,
775 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
776 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
777 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
778 .Times(1);
779 manager_->RefreshPolicies();
780 Mock::VerifyAndClearExpectations(this);
782 // Now, fake a transient error from the server on this policy fetch. This
783 // should have no impact on the cached policy.
784 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
785 em::DeviceManagementResponse());
786 base::RunLoop().RunUntilIdle();
787 ASSERT_TRUE(manager_->IsClientRegistered());
790 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
791 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
793 EXPECT_TRUE(manager_->IsClientRegistered());
794 #if !defined(OS_ANDROID)
795 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
796 #endif
798 // Kick off another policy fetch.
799 MockDeviceManagementJob* fetch_request = NULL;
800 EXPECT_CALL(device_management_service_,
801 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
802 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
803 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
804 .Times(1);
805 manager_->RefreshPolicies();
806 Mock::VerifyAndClearExpectations(this);
808 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
809 // indicates that chrome management is disabled and will result in the cached
810 // policy being removed and the manager shut down.
811 EXPECT_CALL(*mock_store_, Clear());
812 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
813 em::DeviceManagementResponse());
814 base::RunLoop().RunUntilIdle();
815 EXPECT_FALSE(manager_->IsClientRegistered());
816 #if !defined(OS_ANDROID)
817 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
818 #endif
821 } // namespace
823 } // namespace policy