session_manager_operation_unittest.cc revision 0529e5d033099cbfc42635f6f6183833b09dff6e
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 "chrome/browser/chromeos/settings/session_manager_operation.h"
6
7#include "base/basictypes.h"
8#include "base/bind.h"
9#include "base/bind_helpers.h"
10#include "base/memory/ref_counted.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/message_loop/message_loop.h"
13#include "base/time/time.h"
14#include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
15#include "chrome/browser/chromeos/settings/device_settings_test_helper.h"
16#include "chrome/browser/chromeos/settings/mock_owner_key_util.h"
17#include "components/policy/core/common/cloud/cloud_policy_constants.h"
18#include "components/policy/core/common/cloud/cloud_policy_validator.h"
19#include "components/policy/core/common/cloud/policy_builder.h"
20#include "content/public/test/test_browser_thread.h"
21#include "crypto/rsa_private_key.h"
22#include "policy/proto/device_management_backend.pb.h"
23#include "testing/gmock/include/gmock/gmock.h"
24#include "testing/gtest/include/gtest/gtest.h"
25
26namespace em = enterprise_management;
27
28using testing::Mock;
29using testing::_;
30
31namespace chromeos {
32
33class SessionManagerOperationTest : public testing::Test {
34 public:
35  SessionManagerOperationTest()
36      : ui_thread_(content::BrowserThread::UI, &message_loop_),
37        file_thread_(content::BrowserThread::FILE, &message_loop_),
38        owner_key_util_(new MockOwnerKeyUtil()),
39        validated_(false) {}
40
41  virtual void SetUp() OVERRIDE {
42    policy_.payload().mutable_pinned_apps()->add_app_id("fake-app");
43    policy_.Build();
44  }
45
46  MOCK_METHOD2(OnOperationCompleted,
47               void(SessionManagerOperation*, DeviceSettingsService::Status));
48
49  void CheckSuccessfulValidation(
50      policy::DeviceCloudPolicyValidator* validator) {
51    EXPECT_TRUE(validator->success());
52    EXPECT_TRUE(validator->payload().get());
53    EXPECT_EQ(validator->payload()->SerializeAsString(),
54              policy_.payload().SerializeAsString());
55    validated_ = true;
56  }
57
58  void CheckPublicKeyLoaded(SessionManagerOperation* op) {
59    ASSERT_TRUE(op->owner_key().get());
60    ASSERT_TRUE(op->owner_key()->public_key());
61    std::vector<uint8> public_key;
62    ASSERT_TRUE(policy_.GetSigningKey()->ExportPublicKey(&public_key));
63    EXPECT_EQ(public_key, *op->owner_key()->public_key());
64  }
65
66  void CheckPrivateKeyLoaded(SessionManagerOperation* op) {
67    ASSERT_TRUE(op->owner_key().get());
68    ASSERT_TRUE(op->owner_key()->private_key());
69    std::vector<uint8> expected_key;
70    ASSERT_TRUE(policy_.GetSigningKey()->ExportPrivateKey(&expected_key));
71    std::vector<uint8> actual_key;
72    ASSERT_TRUE(op->owner_key()->private_key()->ExportPrivateKey(&actual_key));
73    EXPECT_EQ(expected_key, actual_key);
74  }
75
76 protected:
77  base::MessageLoop message_loop_;
78  content::TestBrowserThread ui_thread_;
79  content::TestBrowserThread file_thread_;
80
81  policy::DevicePolicyBuilder policy_;
82  DeviceSettingsTestHelper device_settings_test_helper_;
83  scoped_refptr<MockOwnerKeyUtil> owner_key_util_;
84
85  bool validated_;
86
87 private:
88  DISALLOW_COPY_AND_ASSIGN(SessionManagerOperationTest);
89};
90
91TEST_F(SessionManagerOperationTest, LoadNoPolicyNoKey) {
92  LoadSettingsOperation op(
93      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
94                 base::Unretained(this)));
95
96  EXPECT_CALL(*this,
97              OnOperationCompleted(
98                  &op, DeviceSettingsService::STORE_KEY_UNAVAILABLE));
99  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
100  device_settings_test_helper_.Flush();
101  Mock::VerifyAndClearExpectations(this);
102
103  EXPECT_FALSE(op.policy_data().get());
104  EXPECT_FALSE(op.device_settings().get());
105  ASSERT_TRUE(op.owner_key().get());
106  EXPECT_FALSE(op.owner_key()->public_key());
107  EXPECT_FALSE(op.owner_key()->private_key());
108}
109
110TEST_F(SessionManagerOperationTest, LoadOwnerKey) {
111  owner_key_util_->SetPublicKeyFromPrivateKey(*policy_.GetSigningKey());
112  LoadSettingsOperation op(
113      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
114                 base::Unretained(this)));
115
116  EXPECT_CALL(*this,
117              OnOperationCompleted(
118                  &op, DeviceSettingsService::STORE_NO_POLICY));
119  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
120  device_settings_test_helper_.Flush();
121  Mock::VerifyAndClearExpectations(this);
122
123  CheckPublicKeyLoaded(&op);
124}
125
126TEST_F(SessionManagerOperationTest, LoadPolicy) {
127  owner_key_util_->SetPublicKeyFromPrivateKey(*policy_.GetSigningKey());
128  device_settings_test_helper_.set_policy_blob(policy_.GetBlob());
129  LoadSettingsOperation op(
130      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
131                 base::Unretained(this)));
132
133  EXPECT_CALL(*this,
134              OnOperationCompleted(
135                  &op, DeviceSettingsService::STORE_SUCCESS));
136  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
137  device_settings_test_helper_.Flush();
138  Mock::VerifyAndClearExpectations(this);
139
140  ASSERT_TRUE(op.policy_data().get());
141  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
142            op.policy_data()->SerializeAsString());
143  ASSERT_TRUE(op.device_settings().get());
144  EXPECT_EQ(policy_.payload().SerializeAsString(),
145            op.device_settings()->SerializeAsString());
146}
147
148TEST_F(SessionManagerOperationTest, LoadPrivateOwnerKey) {
149  owner_key_util_->SetPrivateKey(policy_.GetSigningKey());
150  LoadSettingsOperation op(
151      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
152                 base::Unretained(this)));
153
154  EXPECT_CALL(*this,
155              OnOperationCompleted(
156                  &op, DeviceSettingsService::STORE_NO_POLICY));
157  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
158  device_settings_test_helper_.Flush();
159  Mock::VerifyAndClearExpectations(this);
160
161  CheckPublicKeyLoaded(&op);
162  CheckPrivateKeyLoaded(&op);
163}
164
165TEST_F(SessionManagerOperationTest, RestartLoad) {
166  owner_key_util_->SetPrivateKey(policy_.GetSigningKey());
167  device_settings_test_helper_.set_policy_blob(policy_.GetBlob());
168  LoadSettingsOperation op(
169      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
170                 base::Unretained(this)));
171
172  EXPECT_CALL(*this, OnOperationCompleted(&op, _)).Times(0);
173  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
174  device_settings_test_helper_.FlushLoops();
175  device_settings_test_helper_.FlushRetrieve();
176  EXPECT_TRUE(op.owner_key().get());
177  EXPECT_TRUE(op.owner_key()->public_key());
178  Mock::VerifyAndClearExpectations(this);
179
180  // Now install a different key and policy and restart the operation.
181  policy_.SetSigningKey(*policy::PolicyBuilder::CreateTestOtherSigningKey());
182  policy_.payload().mutable_metrics_enabled()->set_metrics_enabled(true);
183  policy_.Build();
184  device_settings_test_helper_.set_policy_blob(policy_.GetBlob());
185  owner_key_util_->SetPrivateKey(policy_.GetSigningKey());
186
187  EXPECT_CALL(*this,
188              OnOperationCompleted(
189                  &op, DeviceSettingsService::STORE_SUCCESS));
190  op.RestartLoad(true);
191  device_settings_test_helper_.Flush();
192  Mock::VerifyAndClearExpectations(this);
193
194  // Check that the new keys have been loaded.
195  CheckPublicKeyLoaded(&op);
196  CheckPrivateKeyLoaded(&op);
197
198  // Verify the new policy.
199  ASSERT_TRUE(op.policy_data().get());
200  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
201            op.policy_data()->SerializeAsString());
202  ASSERT_TRUE(op.device_settings().get());
203  EXPECT_EQ(policy_.payload().SerializeAsString(),
204            op.device_settings()->SerializeAsString());
205}
206
207TEST_F(SessionManagerOperationTest, StoreSettings) {
208  owner_key_util_->SetPublicKeyFromPrivateKey(*policy_.GetSigningKey());
209  StoreSettingsOperation op(
210      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
211                 base::Unretained(this)),
212      policy_.GetCopy());
213
214  EXPECT_CALL(*this,
215              OnOperationCompleted(
216                  &op, DeviceSettingsService::STORE_SUCCESS));
217  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
218  device_settings_test_helper_.Flush();
219  Mock::VerifyAndClearExpectations(this);
220
221  EXPECT_EQ(device_settings_test_helper_.policy_blob(),
222            policy_.GetBlob());
223  ASSERT_TRUE(op.policy_data().get());
224  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
225            op.policy_data()->SerializeAsString());
226  ASSERT_TRUE(op.device_settings().get());
227  EXPECT_EQ(policy_.payload().SerializeAsString(),
228            op.device_settings()->SerializeAsString());
229}
230
231TEST_F(SessionManagerOperationTest, SignAndStoreSettings) {
232  owner_key_util_->SetPrivateKey(policy_.GetSigningKey());
233  scoped_ptr<em::PolicyData> policy(new em::PolicyData(policy_.policy_data()));
234  SignAndStoreSettingsOperation op(
235      base::Bind(&SessionManagerOperationTest::OnOperationCompleted,
236                 base::Unretained(this)),
237      policy.Pass());
238
239  EXPECT_CALL(*this,
240              OnOperationCompleted(
241                  &op, DeviceSettingsService::STORE_SUCCESS));
242  op.Start(&device_settings_test_helper_, owner_key_util_, NULL);
243  device_settings_test_helper_.Flush();
244  Mock::VerifyAndClearExpectations(this);
245
246  // The blob should validate.
247  scoped_ptr<em::PolicyFetchResponse> policy_response(
248      new em::PolicyFetchResponse());
249  ASSERT_TRUE(
250      policy_response->ParseFromString(
251          device_settings_test_helper_.policy_blob()));
252  policy::DeviceCloudPolicyValidator* validator =
253      policy::DeviceCloudPolicyValidator::Create(
254          policy_response.Pass(), message_loop_.message_loop_proxy());
255  validator->ValidateUsername(policy_.policy_data().username(), true);
256  const base::Time expected_time = base::Time::UnixEpoch() +
257      base::TimeDelta::FromMilliseconds(policy::PolicyBuilder::kFakeTimestamp);
258  validator->ValidateTimestamp(
259      expected_time,
260      expected_time,
261      policy::CloudPolicyValidatorBase::TIMESTAMP_REQUIRED);
262  validator->ValidatePolicyType(policy::dm_protocol::kChromeDevicePolicyType);
263  validator->ValidatePayload();
264  std::vector<uint8> public_key;
265  policy_.GetSigningKey()->ExportPublicKey(&public_key);
266  // Convert from bytes to string format (which is what ValidateSignature()
267  // takes).
268  std::string public_key_as_string = std::string(
269      reinterpret_cast<const char*>(vector_as_array(&public_key)),
270      public_key.size());
271  validator->ValidateSignature(
272      public_key_as_string,
273      policy::GetPolicyVerificationKey(),
274      policy::PolicyBuilder::kFakeDomain,
275      false);
276  validator->StartValidation(
277      base::Bind(&SessionManagerOperationTest::CheckSuccessfulValidation,
278                 base::Unretained(this)));
279
280  message_loop_.RunUntilIdle();
281  EXPECT_TRUE(validated_);
282
283  // Loaded device settings should match what the operation received.
284  ASSERT_TRUE(op.device_settings().get());
285  EXPECT_EQ(policy_.payload().SerializeAsString(),
286            op.device_settings()->SerializeAsString());
287}
288
289}  // namespace chromeos
290