summaryrefslogtreecommitdiffstats
path: root/chrome/browser/policy/cloud_policy_controller_unittest.cc
blob: e752bc9b7b9dcd315f974dfd881574f8b77f91fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/cloud_policy_controller.h"

#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/device_token_fetcher.h"
#include "chrome/browser/policy/logging_work_scheduler.h"
#include "chrome/browser/policy/mock_device_management_service.h"
#include "chrome/browser/policy/policy_notifier.h"
#include "chrome/browser/policy/proto/cloud_policy.pb.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/policy/user_policy_cache.h"
#include "content/public/test/test_browser_thread.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace em = enterprise_management;

namespace policy {

using ::testing::AnyNumber;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::_;
using content::BrowserThread;

class MockDeviceTokenFetcher : public DeviceTokenFetcher {
 public:
  explicit MockDeviceTokenFetcher(CloudPolicyCacheBase* cache)
      : DeviceTokenFetcher(NULL, cache, NULL, NULL) {}
  virtual ~MockDeviceTokenFetcher() {}

  MOCK_METHOD0(FetchToken, void());
  MOCK_METHOD0(SetUnmanagedState, void());
  MOCK_METHOD0(SetSerialNumberInvalidState, void());
  MOCK_METHOD0(SetMissingLicensesState, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockDeviceTokenFetcher);
};

class CloudPolicyControllerTest : public testing::Test {
 public:
  CloudPolicyControllerTest()
      : ui_thread_(BrowserThread::UI, &loop_),
        file_thread_(BrowserThread::FILE, &loop_) {
    em::PolicyData signed_response;
    em::CloudPolicySettings settings;
    em::DisableSpdyProto* spdy_proto = settings.mutable_disablespdy();
    spdy_proto->set_disablespdy(true);
    spdy_proto->mutable_policy_options()->set_mode(
        em::PolicyOptions::MANDATORY);
    EXPECT_TRUE(
        settings.SerializeToString(signed_response.mutable_policy_value()));
    base::TimeDelta timestamp =
        base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
    signed_response.set_timestamp(timestamp.InMilliseconds());
    std::string serialized_signed_response;
    EXPECT_TRUE(signed_response.SerializeToString(&serialized_signed_response));
    em::PolicyFetchResponse* fetch_response =
        spdy_policy_response_.mutable_policy_response()->add_response();
    fetch_response->set_policy_data(serialized_signed_response);
  }

  virtual ~CloudPolicyControllerTest() {}

  virtual void SetUp() {
    ASSERT_TRUE(temp_user_data_dir_.CreateUniqueTempDir());
    cache_.reset(new UserPolicyCache(
        temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest"),
        false  /* wait_for_policy_fetch */));
    token_fetcher_.reset(new MockDeviceTokenFetcher(cache_.get()));
    EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)).Times(AnyNumber());
    data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies());
  }

  virtual void TearDown() {
    controller_.reset();  // Unregisters observers.
    data_store_.reset();
  }

  void CreateNewController() {
    controller_.reset(new CloudPolicyController(
        &service_, cache_.get(), token_fetcher_.get(), data_store_.get(),
        &notifier_, new DummyWorkScheduler));
  }

  void CreateNewWaitingCache() {
    cache_.reset(new UserPolicyCache(
        temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest"),
        true  /* wait_for_policy_fetch */));
    // Make this cache's disk cache ready, but have it still waiting for a
    // policy fetch.
    cache_->Load();
    loop_.RunAllPending();
    ASSERT_TRUE(cache_->last_policy_refresh_time().is_null());
    ASSERT_FALSE(cache_->IsReady());
  }

  void ExpectHasSpdyPolicy() {
    base::FundamentalValue expected(true);
    ASSERT_TRUE(Value::Equals(&expected,
                              cache_->policy()->GetValue(key::kDisableSpdy)));
  }

 protected:
  scoped_ptr<CloudPolicyCacheBase> cache_;
  scoped_ptr<CloudPolicyController> controller_;
  scoped_ptr<MockDeviceTokenFetcher> token_fetcher_;
  scoped_ptr<CloudPolicyDataStore> data_store_;
  MockDeviceManagementService service_;
  PolicyNotifier notifier_;
  base::ScopedTempDir temp_user_data_dir_;
  MessageLoop loop_;
  em::DeviceManagementResponse spdy_policy_response_;

 private:
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;

  DISALLOW_COPY_AND_ASSIGN(CloudPolicyControllerTest);
};

// If a device token is present when the controller starts up, it should
// fetch and apply policy.
TEST_F(CloudPolicyControllerTest, StartupWithDeviceToken) {
  data_store_->SetupForTesting("fake_device_token", "device_id", "", "",
                               true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                      service_.SucceedJob(spdy_policy_response_)));
  CreateNewController();
  loop_.RunAllPending();
  ExpectHasSpdyPolicy();
}

// If no device token is present when the controller starts up, it should
// instruct the token_fetcher_ to fetch one.
TEST_F(CloudPolicyControllerTest, StartupWithoutDeviceToken) {
  data_store_->SetupForTesting("", "device_id", "a@b.com", "auth_token",
                               true);
  EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the current user belongs to a known non-managed domain, no token fetch
// should be initiated.
TEST_F(CloudPolicyControllerTest, StartupUnmanagedUser) {
  data_store_->SetupForTesting("", "device_id", "DannoHelper@gmail.com",
                               "auth_token", true);
  EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(0);
  CreateNewController();
  loop_.RunAllPending();
}

// After policy has been fetched successfully, a new fetch should be triggered
// after the refresh interval has timed out.
TEST_F(CloudPolicyControllerTest, RefreshAfterSuccessfulPolicy) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "DannoHelperDelegate@b.com",
                               "auth_token", true);
  {
    InSequence s;
    EXPECT_CALL(service_,
                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
        .WillOnce(service_.SucceedJob(spdy_policy_response_));
    EXPECT_CALL(service_,
                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
        .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                        service_.FailJob(DM_STATUS_REQUEST_FAILED)));
  }
  CreateNewController();
  loop_.RunAllPending();
  ExpectHasSpdyPolicy();
}

// If policy fetching failed, it should be retried.
TEST_F(CloudPolicyControllerTest, RefreshAfterError) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "DannoHelperDelegateImpl@b.com",
                               "auth_token", true);
  {
    InSequence s;
    EXPECT_CALL(service_,
                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
        .WillOnce(service_.FailJob(DM_STATUS_REQUEST_FAILED));
    EXPECT_CALL(service_,
                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
        .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                        service_.SucceedJob(spdy_policy_response_)));
  }
  CreateNewController();
  loop_.RunAllPending();
  ExpectHasSpdyPolicy();
}

// If the backend reports that the device token was invalid, the controller
// should instruct the token fetcher to fetch a new token.
TEST_F(CloudPolicyControllerTest, InvalidToken) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "standup@ten.am", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID));
  EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the backend reports that the device is unknown to the server, the
// controller should instruct the token fetcher to fetch a new token.
TEST_F(CloudPolicyControllerTest, DeviceNotFound) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "me@you.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_DEVICE_NOT_FOUND));
  EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the backend reports that the device-id is already existing, the
// controller should instruct the token fetcher to fetch a new token.
TEST_F(CloudPolicyControllerTest, DeviceIdConflict) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "me@you.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_DEVICE_ID_CONFLICT));
  EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the backend reports that the device is no longer managed, the controller
// should instruct the token fetcher to fetch a new token (which will in turn
// set and persist the correct 'unmanaged' state).
TEST_F(CloudPolicyControllerTest, NoLongerManaged) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "who@what.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED));
  EXPECT_CALL(*token_fetcher_.get(), SetUnmanagedState()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the backend reports that the device has invalid serial number, the
// controller should instruct the token fetcher not to fetch a new token
// (which will in turn set and persist the correct 'sn invalid' state).
TEST_F(CloudPolicyControllerTest, InvalidSerialNumber) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "who@what.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER));
  EXPECT_CALL(*token_fetcher_.get(), SetSerialNumberInvalidState()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

// If the backend reports that the domain has run out of licenses, the
// controller should instruct the token fetcher not to fetch a new token
// (which will in turn set and persist the correct 'missing licenses' state).
TEST_F(CloudPolicyControllerTest, MissingLicenses) {
  data_store_->SetupForTesting("device_token", "device_id",
                               "who@what.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(service_.FailJob(DM_STATUS_SERVICE_MISSING_LICENSES));
  EXPECT_CALL(*token_fetcher_.get(), SetMissingLicensesState()).Times(1);
  CreateNewController();
  loop_.RunAllPending();
}

TEST_F(CloudPolicyControllerTest, DontSetFetchingDoneWithoutTokens) {
  CreateNewWaitingCache();
  CreateNewController();
  // Initialized without an oauth token, goes into TOKEN_UNAVAILABLE state.
  // This means the controller is still waiting for an oauth token fetch.
  loop_.RunAllPending();
  EXPECT_FALSE(cache_->IsReady());

  controller_->OnDeviceTokenChanged();
  loop_.RunAllPending();
  EXPECT_FALSE(cache_->IsReady());
}

TEST_F(CloudPolicyControllerTest, RefreshPoliciesWithoutMaterial) {
  CreateNewWaitingCache();
  CreateNewController();
  loop_.RunAllPending();
  EXPECT_FALSE(cache_->IsReady());

  // Same scenario as the last test, but the RefreshPolicies call must always
  // notify the cache.
  controller_->RefreshPolicies(false);
  loop_.RunAllPending();
  EXPECT_TRUE(cache_->IsReady());
}

TEST_F(CloudPolicyControllerTest, DontSetFetchingDoneWithoutFetching) {
  CreateNewWaitingCache();
  data_store_->SetupForTesting("device_token", "device_id",
                               "who@what.com", "auth", true);
  CreateNewController();
  // Initialized with an oauth token, goes into TOKEN_VALID state.
  // This means the controller has an oauth token and should fetch the next
  // token, which is the dm server register token.
  EXPECT_FALSE(cache_->IsReady());
}

TEST_F(CloudPolicyControllerTest, SetFetchingDoneForUnmanagedUsers) {
  CreateNewWaitingCache();
  data_store_->SetupForTesting("", "device_id",
                               "user@gmail.com", "auth", true);
  CreateNewController();
  loop_.RunAllPending();
  // User is in an unmanaged domain.
  EXPECT_TRUE(cache_->IsReady());
  EXPECT_TRUE(cache_->last_policy_refresh_time().is_null());
}

TEST_F(CloudPolicyControllerTest, SetFetchingDoneAfterPolicyFetch) {
  CreateNewWaitingCache();
  data_store_->SetupForTesting("device_token", "device_id",
                               "user@enterprise.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                      service_.SucceedJob(spdy_policy_response_)));
  CreateNewController();
  loop_.RunAllPending();
  EXPECT_TRUE(cache_->IsReady());
  EXPECT_FALSE(cache_->last_policy_refresh_time().is_null());
}

TEST_F(CloudPolicyControllerTest, SetFetchingDoneAfterPolicyFetchFails) {
  CreateNewWaitingCache();
  data_store_->SetupForTesting("device_token", "device_id",
                               "user@enterprise.com", "auth", true);
  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                      service_.FailJob(DM_STATUS_REQUEST_FAILED)));
  CreateNewController();
  loop_.RunAllPending();
  EXPECT_TRUE(cache_->IsReady());
  EXPECT_TRUE(cache_->last_policy_refresh_time().is_null());
}

TEST_F(CloudPolicyControllerTest, DelayRefreshesIfPolicyIsInvalid) {
  // Reply with a protobuf whose timestamp is too far in the future. The policy
  // cache will reject it, and the controller should detect that and go into
  // STATE_POLICY_ERROR instead of STATE_POLICY_VALID.

  // Build the |response|.
  em::DeviceManagementResponse response;
  em::PolicyData data;
  em::CloudPolicySettings settings;
  EXPECT_TRUE(settings.SerializeToString(data.mutable_policy_value()));
  base::Time far_in_the_future =
      base::Time::NowFromSystemTime() + base::TimeDelta::FromDays(42);
  base::TimeDelta timestamp = far_in_the_future - base::Time::UnixEpoch();
  data.set_timestamp(timestamp.InMilliseconds());
  std::string serialized_data;
  EXPECT_TRUE(data.SerializeToString(&serialized_data));
  em::PolicyFetchResponse* fetch_response =
      response.mutable_policy_response()->add_response();
  fetch_response->set_policy_data(serialized_data);

  data_store_->SetupForTesting("device_token", "device_id",
                               "madmax@managedchrome.com",
                               "auth_token", true);

  EXPECT_CALL(service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop_, &MessageLoop::QuitNow),
                      service_.SucceedJob(response)));
  CreateNewController();
  loop_.RunAllPending();
  EXPECT_EQ(CloudPolicySubsystem::NETWORK_ERROR, notifier_.state());
  EXPECT_EQ(CloudPolicySubsystem::POLICY_NETWORK_ERROR,
            notifier_.error_details());
}

}  // namespace policy