Convert remoting_unittests to run exclusively on Swarming
[chromium-blink-merge.git] / chrome / browser / policy / cloud / user_policy_signin_service_unittest.cc
blobaf496a060a4fdfc447fedda21fa08399b22eec6f
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_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/account_tracker_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 class SigninManagerFake : public FakeSigninManager {
87 public:
88 explicit SigninManagerFake(Profile* profile)
89 : FakeSigninManager(profile) {
90 Initialize(NULL);
93 void ForceSignOut() {
94 // Allow signing out now.
95 prohibit_signout_ = false;
96 SignOut(signin_metrics::SIGNOUT_TEST);
99 static scoped_ptr<KeyedService> Build(content::BrowserContext* profile) {
100 return make_scoped_ptr(
101 new SigninManagerFake(static_cast<Profile*>(profile)));
105 UserCloudPolicyManager* BuildCloudPolicyManager(
106 content::BrowserContext* context) {
107 MockUserCloudPolicyStore* store = new MockUserCloudPolicyStore();
108 EXPECT_CALL(*store, Load()).Times(AnyNumber());
110 return new UserCloudPolicyManager(
111 scoped_ptr<UserCloudPolicyStore>(store),
112 base::FilePath(),
113 scoped_ptr<CloudExternalDataManager>(),
114 base::ThreadTaskRunnerHandle::Get(),
115 base::ThreadTaskRunnerHandle::Get(),
116 base::ThreadTaskRunnerHandle::Get());
119 class UserPolicySigninServiceTest : public testing::Test {
120 public:
121 UserPolicySigninServiceTest()
122 : mock_store_(NULL),
123 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
124 register_completed_(false) {}
126 MOCK_METHOD1(OnPolicyRefresh, void(bool));
128 void OnRegisterCompleted(const std::string& dm_token,
129 const std::string& client_id) {
130 register_completed_ = true;
131 dm_token_ = dm_token;
132 client_id_ = client_id;
135 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
136 // Policy client registration on Android depends on Token Service having
137 // a valid login token, while on other platforms, the login refresh token
138 // is specified directly.
139 #if defined(OS_ANDROID)
140 GetTokenService()->IssueRefreshTokenForUser(
141 AccountTrackerService::PickAccountIdForAccount(
142 profile_.get()->GetPrefs(), kTestGaiaId, kTestUser),
143 "oauth2_login_refresh_token");
144 #endif
145 service->RegisterForPolicy(
146 kTestUser,
147 #if !defined(OS_ANDROID)
148 "mock_oauth_token",
149 #endif
150 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
151 base::Unretained(this)));
152 ASSERT_TRUE(IsRequestActive());
155 void SetUp() override {
156 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
157 &device_management_service_);
159 local_state_.reset(new TestingPrefServiceSimple);
160 chrome::RegisterLocalState(local_state_->registry());
161 system_request_context_getter_ = new net::TestURLRequestContextGetter(
162 base::ThreadTaskRunnerHandle::Get());
163 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
164 system_request_context_getter_.get());
165 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
167 g_browser_process->browser_policy_connector()->Init(
168 local_state_.get(), system_request_context_getter_);
170 // Create a testing profile with cloud-policy-on-signin enabled, and bring
171 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
172 scoped_ptr<TestingPrefServiceSyncable> prefs(
173 new TestingPrefServiceSyncable());
174 chrome::RegisterUserProfilePrefs(prefs->registry());
176 // UserCloudPolicyManagerFactory isn't a real
177 // BrowserContextKeyedServiceFactory (it derives from
178 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
179 // instances) so we have to inject our testing factory via a special
180 // API before creating the profile.
181 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
182 BuildCloudPolicyManager);
183 TestingProfile::Builder builder;
184 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
185 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
186 SigninManagerFake::Build);
187 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
188 BuildFakeProfileOAuth2TokenService);
189 builder.AddTestingFactory(AccountTrackerServiceFactory::GetInstance(),
190 FakeAccountTrackerService::Build);
191 builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(),
192 signin::BuildTestSigninClient);
194 profile_ = builder.Build().Pass();
195 url_factory_.set_remove_fetcher_on_delete(true);
197 signin_manager_ = static_cast<SigninManagerFake*>(
198 SigninManagerFactory::GetForProfile(profile_.get()));
199 // Tests are responsible for freeing the UserCloudPolicyManager instances
200 // they inject.
201 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
202 profile_.get()));
203 manager_->Init(&schema_registry_);
204 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
205 manager_->core()->store());
206 DCHECK(mock_store_);
207 AddProfile();
209 Mock::VerifyAndClearExpectations(mock_store_);
212 void TearDown() override {
213 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
214 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
215 // Free the profile before we clear out the browser prefs.
216 profile_.reset();
217 TestingBrowserProcess* testing_browser_process =
218 TestingBrowserProcess::GetGlobal();
219 testing_browser_process->SetLocalState(NULL);
220 local_state_.reset();
221 testing_browser_process->SetBrowserPolicyConnector(NULL);
222 base::RunLoop run_loop;
223 run_loop.RunUntilIdle();
226 virtual void AddProfile() {
227 // For this test, the user should not be signed in yet.
228 DCHECK(!signin_manager_->IsAuthenticated());
230 // Initializing UserPolicySigninService while the user is not signed in
231 // should result in the store being cleared to remove any lingering policy.
232 EXPECT_CALL(*mock_store_, Clear());
234 // Let the SigninService know that the profile has been created.
235 content::NotificationService::current()->Notify(
236 chrome::NOTIFICATION_PROFILE_ADDED,
237 content::Source<Profile>(profile_.get()),
238 content::NotificationService::NoDetails());
241 FakeProfileOAuth2TokenService* GetTokenService() {
242 ProfileOAuth2TokenService* service =
243 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
244 return static_cast<FakeProfileOAuth2TokenService*>(service);
247 bool IsRequestActive() {
248 if (!GetTokenService()->GetPendingRequests().empty())
249 return true;
250 return url_factory_.GetFetcherByID(0);
253 void MakeOAuthTokenFetchSucceed() {
254 ASSERT_TRUE(IsRequestActive());
255 #if defined(OS_ANDROID)
256 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
257 base::Time::Now());
258 #else
259 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
260 fetcher->set_response_code(net::HTTP_OK);
261 fetcher->SetResponseString(kValidTokenResponse);
262 fetcher->delegate()->OnURLFetchComplete(fetcher);
263 #endif
266 void ReportHostedDomainStatus(bool is_hosted_domain) {
267 ASSERT_TRUE(IsRequestActive());
268 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
269 fetcher->set_response_code(net::HTTP_OK);
270 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
271 fetcher->delegate()->OnURLFetchComplete(fetcher);
274 void TestSuccessfulSignin() {
275 UserPolicySigninService* signin_service =
276 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
277 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
278 RegisterPolicyClientWithCallback(signin_service);
280 // Mimic successful oauth token fetch.
281 MakeOAuthTokenFetchSucceed();
283 // When the user is from a hosted domain, this should kick off client
284 // registration.
285 MockDeviceManagementJob* register_request = NULL;
286 EXPECT_CALL(device_management_service_,
287 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
288 .WillOnce(device_management_service_.CreateAsyncJob(
289 &register_request));
290 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
291 .Times(1);
293 // Now mimic the user being a hosted domain - this should cause a Register()
294 // call.
295 ReportHostedDomainStatus(true);
297 // Should have no more outstanding requests.
298 ASSERT_FALSE(IsRequestActive());
299 Mock::VerifyAndClearExpectations(this);
300 ASSERT_TRUE(register_request);
302 // Mimic successful client registration - this should register the client
303 // and invoke the callback.
304 em::DeviceManagementResponse registration_blob;
305 std::string expected_dm_token = "dm_token";
306 registration_blob.mutable_register_response()->set_device_management_token(
307 expected_dm_token);
308 registration_blob.mutable_register_response()->set_enrollment_type(
309 em::DeviceRegisterResponse::ENTERPRISE);
310 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
312 // UserCloudPolicyManager should not be initialized yet.
313 ASSERT_FALSE(manager_->core()->service());
314 EXPECT_TRUE(register_completed_);
315 EXPECT_EQ(dm_token_, expected_dm_token);
317 // Now call to fetch policy - this should fire off a fetch request.
318 MockDeviceManagementJob* fetch_request = NULL;
319 EXPECT_CALL(device_management_service_,
320 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
321 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
322 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
323 .Times(1);
325 signin_service->FetchPolicyForSignedInUser(
326 kTestUser,
327 dm_token_,
328 client_id_,
329 profile_->GetRequestContext(),
330 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
331 base::Unretained(this)));
333 Mock::VerifyAndClearExpectations(this);
334 ASSERT_TRUE(fetch_request);
336 // UserCloudPolicyManager should now be initialized.
337 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
338 ASSERT_TRUE(manager_->core()->service());
340 // Make the policy fetch succeed - this should result in a write to the
341 // store and ultimately result in a call to OnPolicyRefresh().
342 EXPECT_CALL(*mock_store_, Store(_));
343 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
345 // Create a fake policy blob to deliver to the client.
346 em::DeviceManagementResponse policy_blob;
347 em::PolicyData policy_data;
348 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
349 em::PolicyFetchResponse* policy_response =
350 policy_blob.mutable_policy_response()->add_response();
351 ASSERT_TRUE(policy_data.SerializeToString(
352 policy_response->mutable_policy_data()));
353 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
355 // Complete the store which should cause the policy fetch callback to be
356 // invoked.
357 mock_store_->NotifyStoreLoaded();
358 Mock::VerifyAndClearExpectations(this);
361 scoped_ptr<TestingProfile> profile_;
362 MockUserCloudPolicyStore* mock_store_; // Not owned.
363 SchemaRegistry schema_registry_;
364 scoped_ptr<UserCloudPolicyManager> manager_;
366 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
367 // various components asynchronously via tasks, so create fake threads here.
368 content::TestBrowserThreadBundle thread_bundle_;
370 net::TestURLFetcherFactory url_factory_;
372 SigninManagerFake* signin_manager_;
374 // Used in conjunction with OnRegisterCompleted() to test client registration
375 // callbacks.
376 std::string dm_token_;
377 std::string client_id_;
379 // True if OnRegisterCompleted() was called.
380 bool register_completed_;
382 // Weak ptr to the MockDeviceManagementService (object is owned by the
383 // BrowserPolicyConnector).
384 MockDeviceManagementService device_management_service_;
386 scoped_ptr<TestingPrefServiceSimple> local_state_;
387 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
390 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
391 public:
392 void AddProfile() override {
393 // UserCloudPolicyManager should not be initialized.
394 ASSERT_FALSE(manager_->core()->service());
396 // Set the user as signed in.
397 SigninManagerFactory::GetForProfile(profile_.get())->
398 SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
400 // Let the SigninService know that the profile has been created.
401 content::NotificationService::current()->Notify(
402 chrome::NOTIFICATION_PROFILE_ADDED,
403 content::Source<Profile>(profile_.get()),
404 content::NotificationService::NoDetails());
408 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
409 // Make sure user is not signed in.
410 ASSERT_FALSE(SigninManagerFactory::GetForProfile(profile_.get())->
411 IsAuthenticated());
413 // UserCloudPolicyManager should not be initialized.
414 ASSERT_FALSE(manager_->core()->service());
417 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
418 // token after signin. Revisit this after figuring how to handle that on
419 // Android.
420 #if !defined(OS_ANDROID)
422 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
423 // UserCloudPolicyManager should be initialized.
424 ASSERT_TRUE(manager_->core()->service());
426 // Complete initialization of the store.
427 mock_store_->NotifyStoreLoaded();
429 // No oauth access token yet, so client registration should be deferred.
430 ASSERT_FALSE(IsRequestActive());
432 // Make oauth token available.
433 GetTokenService()->IssueRefreshTokenForUser(
434 SigninManagerFactory::GetForProfile(profile_.get())
435 ->GetAuthenticatedAccountId(),
436 "oauth_login_refresh_token");
438 // Client registration should be in progress since we now have an oauth token.
439 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
440 ASSERT_TRUE(IsRequestActive());
443 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
444 // UserCloudPolicyManager should be initialized.
445 ASSERT_TRUE(manager_->core()->service());
447 // Complete initialization of the store.
448 mock_store_->NotifyStoreLoaded();
450 // No oauth access token yet, so client registration should be deferred.
451 ASSERT_FALSE(IsRequestActive());
453 // Make oauth token available.
454 GetTokenService()->IssueRefreshTokenForUser(
455 SigninManagerFactory::GetForProfile(profile_.get())
456 ->GetAuthenticatedAccountId(),
457 "oauth_login_refresh_token");
459 // Client registration should be in progress since we now have an oauth token.
460 ASSERT_TRUE(IsRequestActive());
462 // Now fail the access token fetch.
463 GoogleServiceAuthError error(
464 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
465 GetTokenService()->IssueErrorForAllPendingRequests(error);
466 ASSERT_FALSE(IsRequestActive());
469 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
470 // UserCloudPolicyManager should not be initialized since there is no
471 // signed-in user.
472 ASSERT_FALSE(manager_->core()->service());
474 // Now sign in the user.
475 SigninManagerFactory::GetForProfile(profile_.get())
476 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
478 // Complete initialization of the store.
479 mock_store_->NotifyStoreLoaded();
481 // Make oauth token available.
482 GetTokenService()->IssueRefreshTokenForUser(
483 SigninManagerFactory::GetForProfile(profile_.get())
484 ->GetAuthenticatedAccountId(),
485 "oauth_login_refresh_token");
487 // UserCloudPolicyManager should be initialized.
488 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
489 ASSERT_TRUE(manager_->core()->service());
491 // Client registration should be in progress since we have an oauth token.
492 ASSERT_TRUE(IsRequestActive());
495 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
496 // UserCloudPolicyManager should not be initialized since there is no
497 // signed-in user.
498 ASSERT_FALSE(manager_->core()->service());
500 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
501 SigninManagerFactory::GetForProfile(profile_.get())
502 ->SetAuthenticatedAccountInfo("gaia-id-non_enterprise_user@gmail.com",
503 "non_enterprise_user@gmail.com");
505 // Complete initialization of the store.
506 mock_store_->NotifyStoreLoaded();
508 // Make oauth token available.
509 GetTokenService()->IssueRefreshTokenForUser(
510 SigninManagerFactory::GetForProfile(profile_.get())
511 ->GetAuthenticatedAccountId(),
512 "oauth_login_refresh_token");
514 // UserCloudPolicyManager should not be initialized and there should be no
515 // DMToken request active.
516 ASSERT_TRUE(!manager_->core()->service());
517 ASSERT_FALSE(IsRequestActive());
520 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
521 // UserCloudPolicyManager should not be initialized since there is no
522 // signed-in user.
523 ASSERT_FALSE(manager_->core()->service());
525 // Now sign in the user.
526 SigninManagerFactory::GetForProfile(profile_.get())
527 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
529 // Make oauth token available.
530 GetTokenService()->IssueRefreshTokenForUser(
531 SigninManagerFactory::GetForProfile(profile_.get())
532 ->GetAuthenticatedAccountId(),
533 "oauth_login_refresh_token");
535 // UserCloudPolicyManager should be initialized.
536 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
537 ASSERT_TRUE(manager_->core()->service());
539 // Client registration should not be in progress since the store is not
540 // yet initialized.
541 ASSERT_FALSE(IsRequestActive());
543 // Complete initialization of the store with no policy (unregistered client).
544 mock_store_->NotifyStoreLoaded();
546 // Client registration should be in progress since we have an oauth token.
547 ASSERT_TRUE(IsRequestActive());
550 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
551 // UserCloudPolicyManager should not be initialized since there is no
552 // signed-in user.
553 ASSERT_FALSE(manager_->core()->service());
555 // Now sign in the user.
556 SigninManagerFactory::GetForProfile(profile_.get())
557 ->SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser);
559 // Make oauth token available.
560 GetTokenService()->IssueRefreshTokenForUser(
561 SigninManagerFactory::GetForProfile(profile_.get())
562 ->GetAuthenticatedAccountId(),
563 "oauth_login_refresh_token");
565 // UserCloudPolicyManager should be initialized.
566 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
567 ASSERT_TRUE(manager_->core()->service());
569 // Client registration should not be in progress since the store is not
570 // yet initialized.
571 ASSERT_FALSE(manager_->IsClientRegistered());
572 ASSERT_FALSE(IsRequestActive());
574 mock_store_->policy_.reset(new enterprise_management::PolicyData());
575 mock_store_->policy_->set_request_token("fake token");
576 mock_store_->policy_->set_device_id("fake client id");
578 // Complete initialization of the store.
579 mock_store_->NotifyStoreLoaded();
581 // Client registration should not be in progress since the client should be
582 // already registered.
583 ASSERT_TRUE(manager_->IsClientRegistered());
584 ASSERT_FALSE(IsRequestActive());
587 #endif // !defined(OS_ANDROID)
589 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
590 // UserCloudPolicyManager should be initialized.
591 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
592 ASSERT_TRUE(manager_->core()->service());
594 // Signing out will clear the policy from the store.
595 EXPECT_CALL(*mock_store_, Clear());
597 // Now sign out.
598 SigninManagerFactory::GetForProfile(profile_.get())->SignOut(
599 signin_metrics::SIGNOUT_TEST);
601 // UserCloudPolicyManager should be shut down.
602 ASSERT_FALSE(manager_->core()->service());
605 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
606 UserPolicySigninService* signin_service =
607 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
608 RegisterPolicyClientWithCallback(signin_service);
609 Mock::VerifyAndClearExpectations(this);
611 // UserCloudPolicyManager should not be initialized.
612 ASSERT_FALSE(manager_->core()->service());
613 ASSERT_TRUE(IsRequestActive());
614 EXPECT_FALSE(register_completed_);
616 // Cause the access token fetch to fail - callback should be invoked.
617 #if defined(OS_ANDROID)
618 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
619 GetTokenService()->IssueErrorForAllPendingRequests(
620 GoogleServiceAuthError::FromServiceError("fail"));
621 #else
622 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
623 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
624 fetcher->delegate()->OnURLFetchComplete(fetcher);
625 #endif
627 EXPECT_TRUE(register_completed_);
628 EXPECT_TRUE(dm_token_.empty());
629 EXPECT_FALSE(IsRequestActive());
632 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
633 UserPolicySigninService* signin_service =
634 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
635 RegisterPolicyClientWithCallback(signin_service);
637 // UserCloudPolicyManager should not be initialized.
638 ASSERT_FALSE(manager_->core()->service());
639 ASSERT_TRUE(IsRequestActive());
641 // Cause the access token request to succeed.
642 MakeOAuthTokenFetchSucceed();
644 // Should be a follow-up fetch to check the hosted-domain status.
645 ASSERT_TRUE(IsRequestActive());
646 Mock::VerifyAndClearExpectations(this);
648 EXPECT_FALSE(register_completed_);
650 // Report that the user is not on a hosted domain - callback should be
651 // invoked reporting a failed fetch.
652 ReportHostedDomainStatus(false);
654 // Since this is not a hosted domain, we should not issue a request for a
655 // DMToken.
656 EXPECT_TRUE(register_completed_);
657 EXPECT_TRUE(dm_token_.empty());
658 ASSERT_FALSE(IsRequestActive());
661 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
662 UserPolicySigninService* signin_service =
663 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
664 RegisterPolicyClientWithCallback(signin_service);
666 // UserCloudPolicyManager should not be initialized.
667 ASSERT_FALSE(manager_->core()->service());
669 // Mimic successful oauth token fetch.
670 MakeOAuthTokenFetchSucceed();
672 EXPECT_FALSE(register_completed_);
674 // When the user is from a hosted domain, this should kick off client
675 // registration.
676 MockDeviceManagementJob* register_request = NULL;
677 EXPECT_CALL(device_management_service_,
678 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
679 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
680 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
681 .Times(1);
683 // Now mimic the user being a hosted domain - this should cause a Register()
684 // call.
685 ReportHostedDomainStatus(true);
687 // Should have no more outstanding requests.
688 ASSERT_FALSE(IsRequestActive());
689 Mock::VerifyAndClearExpectations(this);
690 ASSERT_TRUE(register_request);
691 EXPECT_FALSE(register_completed_);
693 // Make client registration fail (hosted domain user that is not managed).
694 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
695 em::DeviceManagementResponse());
696 EXPECT_TRUE(register_completed_);
697 EXPECT_TRUE(dm_token_.empty());
700 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
701 UserPolicySigninService* signin_service =
702 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
703 RegisterPolicyClientWithCallback(signin_service);
705 // Mimic successful oauth token fetch.
706 MakeOAuthTokenFetchSucceed();
708 // When the user is from a hosted domain, this should kick off client
709 // registration.
710 MockDeviceManagementJob* register_request = NULL;
711 EXPECT_CALL(device_management_service_,
712 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
713 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
714 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
715 .Times(1);
717 // Now mimic the user being a hosted domain - this should cause a Register()
718 // call.
719 ReportHostedDomainStatus(true);
721 // Should have no more outstanding requests.
722 ASSERT_FALSE(IsRequestActive());
723 Mock::VerifyAndClearExpectations(this);
724 ASSERT_TRUE(register_request);
725 EXPECT_FALSE(register_completed_);
727 em::DeviceManagementResponse registration_blob;
728 std::string expected_dm_token = "dm_token";
729 registration_blob.mutable_register_response()->set_device_management_token(
730 expected_dm_token);
731 registration_blob.mutable_register_response()->set_enrollment_type(
732 em::DeviceRegisterResponse::ENTERPRISE);
733 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
734 Mock::VerifyAndClearExpectations(this);
735 EXPECT_TRUE(register_completed_);
736 EXPECT_EQ(dm_token_, expected_dm_token);
737 // UserCloudPolicyManager should not be initialized.
738 ASSERT_FALSE(manager_->core()->service());
741 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
742 // Initiate a policy fetch request.
743 MockDeviceManagementJob* fetch_request = NULL;
744 EXPECT_CALL(device_management_service_,
745 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
746 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
747 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
748 .Times(1);
749 UserPolicySigninService* signin_service =
750 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
751 signin_service->FetchPolicyForSignedInUser(
752 kTestUser,
753 "mock_dm_token",
754 "mock_client_id",
755 profile_->GetRequestContext(),
756 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
757 base::Unretained(this)));
758 ASSERT_TRUE(fetch_request);
760 // Make the policy fetch fail.
761 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
762 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
763 em::DeviceManagementResponse());
765 // UserCloudPolicyManager should be initialized.
766 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
767 ASSERT_TRUE(manager_->core()->service());
770 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
771 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
774 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
775 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
777 EXPECT_CALL(*mock_store_, Clear());
778 signin_manager_->ForceSignOut();
779 ASSERT_FALSE(manager_->core()->service());
781 // Now sign in again.
782 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
785 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
786 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
788 ASSERT_TRUE(manager_->IsClientRegistered());
790 // Kick off another policy fetch.
791 MockDeviceManagementJob* fetch_request = NULL;
792 EXPECT_CALL(device_management_service_,
793 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
794 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
795 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
796 .Times(1);
797 manager_->RefreshPolicies();
798 Mock::VerifyAndClearExpectations(this);
800 // Now, fake a transient error from the server on this policy fetch. This
801 // should have no impact on the cached policy.
802 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
803 em::DeviceManagementResponse());
804 base::RunLoop().RunUntilIdle();
805 ASSERT_TRUE(manager_->IsClientRegistered());
808 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
809 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
811 EXPECT_TRUE(manager_->IsClientRegistered());
812 #if !defined(OS_ANDROID)
813 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
814 #endif
816 // Kick off another policy fetch.
817 MockDeviceManagementJob* fetch_request = NULL;
818 EXPECT_CALL(device_management_service_,
819 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
820 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
821 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
822 .Times(1);
823 manager_->RefreshPolicies();
824 Mock::VerifyAndClearExpectations(this);
826 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
827 // indicates that chrome management is disabled and will result in the cached
828 // policy being removed and the manager shut down.
829 EXPECT_CALL(*mock_store_, Clear());
830 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
831 em::DeviceManagementResponse());
832 base::RunLoop().RunUntilIdle();
833 EXPECT_FALSE(manager_->IsClientRegistered());
834 #if !defined(OS_ANDROID)
835 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
836 #endif
839 } // namespace
841 } // namespace policy