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