1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/files/file_path.h"
6 #include "base/message_loop/message_loop.h"
7 #include "base/message_loop/message_loop_proxy.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/run_loop.h"
10 #include "base/time/time.h"
11 #include "chrome/browser/browser_process.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
14 #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
15 #include "chrome/browser/prefs/browser_prefs.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
18 #include "chrome/browser/signin/fake_signin_manager.h"
19 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
20 #include "chrome/browser/signin/signin_manager.h"
21 #include "chrome/browser/signin/signin_manager_factory.h"
22 #include "chrome/test/base/testing_browser_process.h"
23 #include "chrome/test/base/testing_pref_service_syncable.h"
24 #include "chrome/test/base/testing_profile.h"
25 #include "components/policy/core/browser/browser_policy_connector.h"
26 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
27 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
28 #include "components/policy/core/common/cloud/mock_device_management_service.h"
29 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
30 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
31 #include "components/policy/core/common/schema_registry.h"
32 #include "content/public/browser/browser_context.h"
33 #include "content/public/browser/notification_details.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_source.h"
36 #include "content/public/test/test_browser_thread_bundle.h"
37 #include "google_apis/gaia/gaia_constants.h"
38 #include "google_apis/gaia/google_service_auth_error.h"
39 #include "net/http/http_status_code.h"
40 #include "net/url_request/test_url_fetcher_factory.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "net/url_request/url_request_status.h"
43 #include "net/url_request/url_request_test_util.h"
44 #include "testing/gmock/include/gmock/gmock.h"
45 #include "testing/gtest/include/gtest/gtest.h"
47 #if defined(OS_ANDROID)
48 #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
50 #include "chrome/browser/policy/cloud/user_policy_signin_service.h"
53 namespace em = enterprise_management;
55 using testing::AnyNumber;
63 const char kTestUser[] = "testuser@test.com";
65 #if !defined(OS_ANDROID)
66 const char kValidTokenResponse[] =
68 " \"access_token\": \"at1\","
69 " \"expires_in\": 3600,"
70 " \"token_type\": \"Bearer\""
74 const char kHostedDomainResponse[] =
76 " \"hd\": \"test.com\""
79 class SigninManagerFake : public FakeSigninManager {
81 explicit SigninManagerFake(Profile* profile)
82 : FakeSigninManager(profile) {
83 Initialize(profile, NULL);
87 // Allow signing out now.
88 prohibit_signout_ = false;
92 static BrowserContextKeyedService* Build(content::BrowserContext* profile) {
93 return new SigninManagerFake(static_cast<Profile*>(profile));
97 UserCloudPolicyManager* BuildCloudPolicyManager(
98 content::BrowserContext* context) {
99 MockUserCloudPolicyStore *store = new MockUserCloudPolicyStore();
100 EXPECT_CALL(*store, Load()).Times(AnyNumber());
102 return new UserCloudPolicyManager(
103 scoped_ptr<UserCloudPolicyStore>(store),
105 scoped_ptr<CloudExternalDataManager>(),
106 base::MessageLoopProxy::current(),
107 base::MessageLoopProxy::current(),
108 base::MessageLoopProxy::current());
111 class UserPolicySigninServiceTest : public testing::Test {
113 UserPolicySigninServiceTest()
115 thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
116 register_completed_(false) {}
118 MOCK_METHOD1(OnPolicyRefresh, void(bool));
120 void OnRegisterCompleted(const std::string& dm_token,
121 const std::string& client_id) {
122 register_completed_ = true;
123 dm_token_ = dm_token;
124 client_id_ = client_id;
127 void RegisterPolicyClientWithCallback(UserPolicySigninService* service) {
128 // Policy client registration on Android depends on Token Service having
129 // a valid login token, while on other platforms, the login refresh token
130 // is specified directly.
131 #if defined(OS_ANDROID)
132 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
133 "oauth2_login_refresh_token");
135 service->RegisterForPolicy(
137 #if !defined(OS_ANDROID)
140 base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted,
141 base::Unretained(this)));
142 ASSERT_TRUE(IsRequestActive());
145 virtual void SetUp() OVERRIDE {
146 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(
147 &device_management_service_);
149 local_state_.reset(new TestingPrefServiceSimple);
150 chrome::RegisterLocalState(local_state_->registry());
151 system_request_context_getter_ = new net::TestURLRequestContextGetter(
152 base::MessageLoopProxy::current());
153 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
154 system_request_context_getter_.get());
155 TestingBrowserProcess::GetGlobal()->SetLocalState(local_state_.get());
157 g_browser_process->browser_policy_connector()->Init(
158 local_state_.get(), system_request_context_getter_);
160 // Create a testing profile with cloud-policy-on-signin enabled, and bring
161 // up a UserCloudPolicyManager with a MockUserCloudPolicyStore.
162 scoped_ptr<TestingPrefServiceSyncable> prefs(
163 new TestingPrefServiceSyncable());
164 chrome::RegisterUserProfilePrefs(prefs->registry());
166 // UserCloudPolicyManagerFactory isn't a real
167 // BrowserContextKeyedServiceFactory (it derives from
168 // BrowserContextKeyedBaseFactory and exposes its own APIs to get
169 // instances) so we have to inject our testing factory via a special
170 // API before creating the profile.
171 UserCloudPolicyManagerFactory::GetInstance()->RegisterTestingFactory(
172 BuildCloudPolicyManager);
173 TestingProfile::Builder builder;
174 builder.SetPrefService(scoped_ptr<PrefServiceSyncable>(prefs.Pass()));
175 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
176 SigninManagerFake::Build);
177 builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
178 FakeProfileOAuth2TokenService::Build);
180 profile_ = builder.Build().Pass();
181 url_factory_.set_remove_fetcher_on_delete(true);
183 signin_manager_ = static_cast<SigninManagerFake*>(
184 SigninManagerFactory::GetForProfile(profile_.get()));
185 // Tests are responsible for freeing the UserCloudPolicyManager instances
187 manager_.reset(UserCloudPolicyManagerFactory::GetForBrowserContext(
189 manager_->Init(&schema_registry_);
190 mock_store_ = static_cast<MockUserCloudPolicyStore*>(
191 manager_->core()->store());
195 Mock::VerifyAndClearExpectations(mock_store_);
198 virtual void TearDown() OVERRIDE {
199 UserPolicySigninServiceFactory::SetDeviceManagementServiceForTesting(NULL);
200 UserCloudPolicyManagerFactory::GetInstance()->ClearTestingFactory();
201 // Free the profile before we clear out the browser prefs.
203 TestingBrowserProcess* testing_browser_process =
204 TestingBrowserProcess::GetGlobal();
205 testing_browser_process->SetLocalState(NULL);
206 local_state_.reset();
207 testing_browser_process->SetBrowserPolicyConnector(NULL);
208 base::RunLoop run_loop;
209 run_loop.RunUntilIdle();
212 virtual void AddProfile() {
213 // For this test, the user should not be signed in yet.
214 DCHECK(signin_manager_->GetAuthenticatedUsername().empty());
216 // Initializing UserPolicySigninService while the user is not signed in
217 // should result in the store being cleared to remove any lingering policy.
218 EXPECT_CALL(*mock_store_, Clear());
220 // Let the SigninService know that the profile has been created.
221 content::NotificationService::current()->Notify(
222 chrome::NOTIFICATION_PROFILE_ADDED,
223 content::Source<Profile>(profile_.get()),
224 content::NotificationService::NoDetails());
227 FakeProfileOAuth2TokenService* GetTokenService() {
228 ProfileOAuth2TokenService* service =
229 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get());
230 return static_cast<FakeProfileOAuth2TokenService*>(service);
233 bool IsRequestActive() {
234 if (!GetTokenService()->GetPendingRequests().empty())
236 return url_factory_.GetFetcherByID(0);
239 void MakeOAuthTokenFetchSucceed() {
240 ASSERT_TRUE(IsRequestActive());
241 #if defined(OS_ANDROID)
242 GetTokenService()->IssueTokenForAllPendingRequests("access_token",
245 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
246 fetcher->set_response_code(net::HTTP_OK);
247 fetcher->SetResponseString(kValidTokenResponse);
248 fetcher->delegate()->OnURLFetchComplete(fetcher);
252 void ReportHostedDomainStatus(bool is_hosted_domain) {
253 ASSERT_TRUE(IsRequestActive());
254 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
255 fetcher->set_response_code(net::HTTP_OK);
256 fetcher->SetResponseString(is_hosted_domain ? kHostedDomainResponse : "{}");
257 fetcher->delegate()->OnURLFetchComplete(fetcher);
260 void TestSuccessfulSignin() {
261 UserPolicySigninService* signin_service =
262 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
263 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(0);
264 RegisterPolicyClientWithCallback(signin_service);
266 // Mimic successful oauth token fetch.
267 MakeOAuthTokenFetchSucceed();
269 // When the user is from a hosted domain, this should kick off client
271 MockDeviceManagementJob* register_request = NULL;
272 EXPECT_CALL(device_management_service_,
273 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
274 .WillOnce(device_management_service_.CreateAsyncJob(
276 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
279 // Now mimic the user being a hosted domain - this should cause a Register()
281 ReportHostedDomainStatus(true);
283 // Should have no more outstanding requests.
284 ASSERT_FALSE(IsRequestActive());
285 Mock::VerifyAndClearExpectations(this);
286 ASSERT_TRUE(register_request);
288 // Mimic successful client registration - this should register the client
289 // and invoke the callback.
290 em::DeviceManagementResponse registration_blob;
291 std::string expected_dm_token = "dm_token";
292 registration_blob.mutable_register_response()->set_device_management_token(
294 registration_blob.mutable_register_response()->set_enrollment_type(
295 em::DeviceRegisterResponse::ENTERPRISE);
296 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
298 // UserCloudPolicyManager should not be initialized yet.
299 ASSERT_FALSE(manager_->core()->service());
300 EXPECT_TRUE(register_completed_);
301 EXPECT_EQ(dm_token_, expected_dm_token);
303 // Now call to fetch policy - this should fire off a fetch request.
304 MockDeviceManagementJob* fetch_request = NULL;
305 EXPECT_CALL(device_management_service_,
306 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
307 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
308 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
311 signin_service->FetchPolicyForSignedInUser(
315 profile_->GetRequestContext(),
316 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
317 base::Unretained(this)));
319 Mock::VerifyAndClearExpectations(this);
320 ASSERT_TRUE(fetch_request);
322 // UserCloudPolicyManager should now be initialized.
323 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
324 ASSERT_TRUE(manager_->core()->service());
326 // Make the policy fetch succeed - this should result in a write to the
327 // store and ultimately result in a call to OnPolicyRefresh().
328 EXPECT_CALL(*mock_store_, Store(_));
329 EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
331 // Create a fake policy blob to deliver to the client.
332 em::DeviceManagementResponse policy_blob;
333 em::PolicyData policy_data;
334 policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType);
335 em::PolicyFetchResponse* policy_response =
336 policy_blob.mutable_policy_response()->add_response();
337 ASSERT_TRUE(policy_data.SerializeToString(
338 policy_response->mutable_policy_data()));
339 fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob);
341 // Complete the store which should cause the policy fetch callback to be
343 mock_store_->NotifyStoreLoaded();
344 Mock::VerifyAndClearExpectations(this);
347 scoped_ptr<TestingProfile> profile_;
348 MockUserCloudPolicyStore* mock_store_; // Not owned.
349 SchemaRegistry schema_registry_;
350 scoped_ptr<UserCloudPolicyManager> manager_;
352 // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free
353 // various components asynchronously via tasks, so create fake threads here.
354 content::TestBrowserThreadBundle thread_bundle_;
356 net::TestURLFetcherFactory url_factory_;
358 SigninManagerFake* signin_manager_;
360 // Used in conjunction with OnRegisterCompleted() to test client registration
362 std::string dm_token_;
363 std::string client_id_;
365 // True if OnRegisterCompleted() was called.
366 bool register_completed_;
368 // Weak ptr to the MockDeviceManagementService (object is owned by the
369 // BrowserPolicyConnector).
370 MockDeviceManagementService device_management_service_;
372 scoped_ptr<TestingPrefServiceSimple> local_state_;
373 scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
376 class UserPolicySigninServiceSignedInTest : public UserPolicySigninServiceTest {
378 virtual void AddProfile() OVERRIDE {
379 // UserCloudPolicyManager should not be initialized.
380 ASSERT_FALSE(manager_->core()->service());
382 // Set the user as signed in.
383 SigninManagerFactory::GetForProfile(profile_.get())->
384 SetAuthenticatedUsername(kTestUser);
386 // Let the SigninService know that the profile has been created.
387 content::NotificationService::current()->Notify(
388 chrome::NOTIFICATION_PROFILE_ADDED,
389 content::Source<Profile>(profile_.get()),
390 content::NotificationService::NoDetails());
394 TEST_F(UserPolicySigninServiceTest, InitWhileSignedOut) {
395 // Make sure user is not signed in.
396 ASSERT_TRUE(SigninManagerFactory::GetForProfile(profile_.get())->
397 GetAuthenticatedUsername().empty());
399 // UserCloudPolicyManager should not be initialized.
400 ASSERT_FALSE(manager_->core()->service());
403 // TODO(joaodasilva): these tests rely on issuing the OAuth2 login refresh
404 // token after signin. Revisit this after figuring how to handle that on
406 #if !defined(OS_ANDROID)
408 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedIn) {
409 // UserCloudPolicyManager should be initialized.
410 ASSERT_TRUE(manager_->core()->service());
412 // Complete initialization of the store.
413 mock_store_->NotifyStoreLoaded();
415 // No oauth access token yet, so client registration should be deferred.
416 ASSERT_FALSE(IsRequestActive());
418 // Make oauth token available.
419 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
420 "oauth_login_refresh_token");
422 // Client registration should be in progress since we now have an oauth token.
423 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
424 ASSERT_TRUE(IsRequestActive());
427 TEST_F(UserPolicySigninServiceSignedInTest, InitWhileSignedInOAuthError) {
428 // UserCloudPolicyManager should be initialized.
429 ASSERT_TRUE(manager_->core()->service());
431 // Complete initialization of the store.
432 mock_store_->NotifyStoreLoaded();
434 // No oauth access token yet, so client registration should be deferred.
435 ASSERT_FALSE(IsRequestActive());
437 // Make oauth token available.
438 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
439 "oauth_login_refresh_token");
441 // Client registration should be in progress since we now have an oauth token.
442 ASSERT_TRUE(IsRequestActive());
444 // Now fail the access token fetch.
445 GoogleServiceAuthError error(
446 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
447 GetTokenService()->IssueErrorForAllPendingRequests(error);
448 ASSERT_FALSE(IsRequestActive());
451 TEST_F(UserPolicySigninServiceTest, SignInAfterInit) {
452 // UserCloudPolicyManager should not be initialized since there is no
454 ASSERT_FALSE(manager_->core()->service());
456 // Now sign in the user.
457 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
460 // Complete initialization of the store.
461 mock_store_->NotifyStoreLoaded();
463 // Make oauth token available.
464 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
465 "oauth_login_refresh_token");
467 // UserCloudPolicyManager should be initialized.
468 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
469 ASSERT_TRUE(manager_->core()->service());
471 // Client registration should be in progress since we have an oauth token.
472 ASSERT_TRUE(IsRequestActive());
475 TEST_F(UserPolicySigninServiceTest, SignInWithNonEnterpriseUser) {
476 // UserCloudPolicyManager should not be initialized since there is no
478 ASSERT_FALSE(manager_->core()->service());
480 // Now sign in a non-enterprise user (blacklisted gmail.com domain).
481 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
482 "non_enterprise_user@gmail.com");
484 // Complete initialization of the store.
485 mock_store_->NotifyStoreLoaded();
487 // Make oauth token available.
488 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
489 "oauth_login_refresh_token");
491 // UserCloudPolicyManager should not be initialized and there should be no
492 // DMToken request active.
493 ASSERT_TRUE(!manager_->core()->service());
494 ASSERT_FALSE(IsRequestActive());
497 TEST_F(UserPolicySigninServiceTest, UnregisteredClient) {
498 // UserCloudPolicyManager should not be initialized since there is no
500 ASSERT_FALSE(manager_->core()->service());
502 // Now sign in the user.
503 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
506 // Make oauth token available.
507 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
508 "oauth_login_refresh_token");
510 // UserCloudPolicyManager should be initialized.
511 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
512 ASSERT_TRUE(manager_->core()->service());
514 // Client registration should not be in progress since the store is not
516 ASSERT_FALSE(IsRequestActive());
518 // Complete initialization of the store with no policy (unregistered client).
519 mock_store_->NotifyStoreLoaded();
521 // Client registration should be in progress since we have an oauth token.
522 ASSERT_TRUE(IsRequestActive());
525 TEST_F(UserPolicySigninServiceTest, RegisteredClient) {
526 // UserCloudPolicyManager should not be initialized since there is no
528 ASSERT_FALSE(manager_->core()->service());
530 // Now sign in the user.
531 SigninManagerFactory::GetForProfile(profile_.get())->SetAuthenticatedUsername(
534 // Make oauth token available.
535 GetTokenService()->IssueRefreshTokenForUser(kTestUser,
536 "oauth_login_refresh_token");
538 // UserCloudPolicyManager should be initialized.
539 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
540 ASSERT_TRUE(manager_->core()->service());
542 // Client registration should not be in progress since the store is not
544 ASSERT_FALSE(manager_->IsClientRegistered());
545 ASSERT_FALSE(IsRequestActive());
547 mock_store_->policy_.reset(new enterprise_management::PolicyData());
548 mock_store_->policy_->set_request_token("fake token");
549 mock_store_->policy_->set_device_id("fake client id");
551 // Complete initialization of the store.
552 mock_store_->NotifyStoreLoaded();
554 // Client registration should not be in progress since the client should be
555 // already registered.
556 ASSERT_TRUE(manager_->IsClientRegistered());
557 ASSERT_FALSE(IsRequestActive());
560 #endif // !defined(OS_ANDROID)
562 TEST_F(UserPolicySigninServiceSignedInTest, SignOutAfterInit) {
563 // UserCloudPolicyManager should be initialized.
564 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
565 ASSERT_TRUE(manager_->core()->service());
567 // Signing out will clear the policy from the store.
568 EXPECT_CALL(*mock_store_, Clear());
571 SigninManagerFactory::GetForProfile(profile_.get())->SignOut();
573 // UserCloudPolicyManager should be shut down.
574 ASSERT_FALSE(manager_->core()->service());
577 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientOAuthFailure) {
578 UserPolicySigninService* signin_service =
579 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
580 RegisterPolicyClientWithCallback(signin_service);
581 Mock::VerifyAndClearExpectations(this);
583 // UserCloudPolicyManager should not be initialized.
584 ASSERT_FALSE(manager_->core()->service());
585 ASSERT_TRUE(IsRequestActive());
586 EXPECT_FALSE(register_completed_);
588 // Cause the access token fetch to fail - callback should be invoked.
589 #if defined(OS_ANDROID)
590 ASSERT_TRUE(!GetTokenService()->GetPendingRequests().empty());
591 GetTokenService()->IssueErrorForAllPendingRequests(
592 GoogleServiceAuthError::FromServiceError("fail"));
594 net::TestURLFetcher* fetcher = url_factory_.GetFetcherByID(0);
595 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
596 fetcher->delegate()->OnURLFetchComplete(fetcher);
599 EXPECT_TRUE(register_completed_);
600 EXPECT_TRUE(dm_token_.empty());
601 EXPECT_FALSE(IsRequestActive());
604 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientNonHostedDomain) {
605 UserPolicySigninService* signin_service =
606 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
607 RegisterPolicyClientWithCallback(signin_service);
609 // UserCloudPolicyManager should not be initialized.
610 ASSERT_FALSE(manager_->core()->service());
611 ASSERT_TRUE(IsRequestActive());
613 // Cause the access token request to succeed.
614 MakeOAuthTokenFetchSucceed();
616 // Should be a follow-up fetch to check the hosted-domain status.
617 ASSERT_TRUE(IsRequestActive());
618 Mock::VerifyAndClearExpectations(this);
620 EXPECT_FALSE(register_completed_);
622 // Report that the user is not on a hosted domain - callback should be
623 // invoked reporting a failed fetch.
624 ReportHostedDomainStatus(false);
626 // Since this is not a hosted domain, we should not issue a request for a
628 EXPECT_TRUE(register_completed_);
629 EXPECT_TRUE(dm_token_.empty());
630 ASSERT_FALSE(IsRequestActive());
633 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientFailedRegistration) {
634 UserPolicySigninService* signin_service =
635 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
636 RegisterPolicyClientWithCallback(signin_service);
638 // UserCloudPolicyManager should not be initialized.
639 ASSERT_FALSE(manager_->core()->service());
641 // Mimic successful oauth token fetch.
642 MakeOAuthTokenFetchSucceed();
644 EXPECT_FALSE(register_completed_);
646 // When the user is from a hosted domain, this should kick off client
648 MockDeviceManagementJob* register_request = NULL;
649 EXPECT_CALL(device_management_service_,
650 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
651 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
652 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
655 // Now mimic the user being a hosted domain - this should cause a Register()
657 ReportHostedDomainStatus(true);
659 // Should have no more outstanding requests.
660 ASSERT_FALSE(IsRequestActive());
661 Mock::VerifyAndClearExpectations(this);
662 ASSERT_TRUE(register_request);
663 EXPECT_FALSE(register_completed_);
665 // Make client registration fail (hosted domain user that is not managed).
666 register_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
667 em::DeviceManagementResponse());
668 EXPECT_TRUE(register_completed_);
669 EXPECT_TRUE(dm_token_.empty());
672 TEST_F(UserPolicySigninServiceTest, RegisterPolicyClientSucceeded) {
673 UserPolicySigninService* signin_service =
674 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
675 RegisterPolicyClientWithCallback(signin_service);
677 // Mimic successful oauth token fetch.
678 MakeOAuthTokenFetchSucceed();
680 // When the user is from a hosted domain, this should kick off client
682 MockDeviceManagementJob* register_request = NULL;
683 EXPECT_CALL(device_management_service_,
684 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
685 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
686 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
689 // Now mimic the user being a hosted domain - this should cause a Register()
691 ReportHostedDomainStatus(true);
693 // Should have no more outstanding requests.
694 ASSERT_FALSE(IsRequestActive());
695 Mock::VerifyAndClearExpectations(this);
696 ASSERT_TRUE(register_request);
697 EXPECT_FALSE(register_completed_);
699 em::DeviceManagementResponse registration_blob;
700 std::string expected_dm_token = "dm_token";
701 registration_blob.mutable_register_response()->set_device_management_token(
703 registration_blob.mutable_register_response()->set_enrollment_type(
704 em::DeviceRegisterResponse::ENTERPRISE);
705 register_request->SendResponse(DM_STATUS_SUCCESS, registration_blob);
706 Mock::VerifyAndClearExpectations(this);
707 EXPECT_TRUE(register_completed_);
708 EXPECT_EQ(dm_token_, expected_dm_token);
709 // UserCloudPolicyManager should not be initialized.
710 ASSERT_FALSE(manager_->core()->service());
713 TEST_F(UserPolicySigninServiceTest, FetchPolicyFailed) {
714 // Initiate a policy fetch request.
715 MockDeviceManagementJob* fetch_request = NULL;
716 EXPECT_CALL(device_management_service_,
717 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
718 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
719 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
721 UserPolicySigninService* signin_service =
722 UserPolicySigninServiceFactory::GetForProfile(profile_.get());
723 signin_service->FetchPolicyForSignedInUser(
727 profile_->GetRequestContext(),
728 base::Bind(&UserPolicySigninServiceTest::OnPolicyRefresh,
729 base::Unretained(this)));
730 ASSERT_TRUE(fetch_request);
732 // Make the policy fetch fail.
733 EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
734 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
735 em::DeviceManagementResponse());
737 // UserCloudPolicyManager should be initialized.
738 EXPECT_EQ(mock_store_->signin_username_, kTestUser);
739 ASSERT_TRUE(manager_->core()->service());
742 TEST_F(UserPolicySigninServiceTest, FetchPolicySuccess) {
743 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
746 TEST_F(UserPolicySigninServiceTest, SignOutThenSignInAgain) {
747 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
749 EXPECT_CALL(*mock_store_, Clear());
750 signin_manager_->ForceSignOut();
751 ASSERT_FALSE(manager_->core()->service());
753 // Now sign in again.
754 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
757 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureTemporary) {
758 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
760 ASSERT_TRUE(manager_->IsClientRegistered());
762 // Kick off another policy fetch.
763 MockDeviceManagementJob* fetch_request = NULL;
764 EXPECT_CALL(device_management_service_,
765 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
766 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
767 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
769 manager_->RefreshPolicies();
770 Mock::VerifyAndClearExpectations(this);
772 // Now, fake a transient error from the server on this policy fetch. This
773 // should have no impact on the cached policy.
774 fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED,
775 em::DeviceManagementResponse());
776 base::RunLoop().RunUntilIdle();
777 ASSERT_TRUE(manager_->IsClientRegistered());
780 TEST_F(UserPolicySigninServiceTest, PolicyFetchFailureDisableManagement) {
781 ASSERT_NO_FATAL_FAILURE(TestSuccessfulSignin());
783 EXPECT_TRUE(manager_->IsClientRegistered());
784 #if !defined(OS_ANDROID)
785 EXPECT_TRUE(signin_manager_->IsSignoutProhibited());
788 // Kick off another policy fetch.
789 MockDeviceManagementJob* fetch_request = NULL;
790 EXPECT_CALL(device_management_service_,
791 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
792 .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
793 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
795 manager_->RefreshPolicies();
796 Mock::VerifyAndClearExpectations(this);
798 // Now, fake a SC_FORBIDDEN error from the server on this policy fetch. This
799 // indicates that chrome management is disabled and will result in the cached
800 // policy being removed and the manager shut down.
801 EXPECT_CALL(*mock_store_, Clear());
802 fetch_request->SendResponse(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED,
803 em::DeviceManagementResponse());
804 base::RunLoop().RunUntilIdle();
805 EXPECT_FALSE(manager_->IsClientRegistered());
806 #if !defined(OS_ANDROID)
807 EXPECT_FALSE(signin_manager_->IsSignoutProhibited());
813 } // namespace policy