1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include "update_engine/omaha_request_action.h"
18
19 #include <stdint.h>
20
21 #include <limits>
22 #include <memory>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27 #include <base/bind.h>
28 #include <base/files/file_util.h>
29 #include <base/files/scoped_temp_dir.h>
30 #include <base/memory/ptr_util.h>
31 #include <base/strings/string_number_conversions.h>
32 #include <base/strings/string_util.h>
33 #include <base/strings/stringprintf.h>
34 #include <base/time/time.h>
35 #include <brillo/message_loops/fake_message_loop.h>
36 #include <brillo/message_loops/message_loop.h>
37 #include <brillo/message_loops/message_loop_utils.h>
38 #include <expat.h>
39 #include <gtest/gtest.h>
40 #include <policy/libpolicy.h>
41 #include <policy/mock_libpolicy.h>
42
43 #include "update_engine/common/action_pipe.h"
44 #include "update_engine/common/constants.h"
45 #include "update_engine/common/fake_prefs.h"
46 #include "update_engine/common/hash_calculator.h"
47 #include "update_engine/common/mock_excluder.h"
48 #include "update_engine/common/mock_http_fetcher.h"
49 #include "update_engine/common/platform_constants.h"
50 #include "update_engine/common/prefs.h"
51 #include "update_engine/common/test_utils.h"
52 #include "update_engine/fake_system_state.h"
53 #include "update_engine/metrics_reporter_interface.h"
54 #include "update_engine/mock_connection_manager.h"
55 #include "update_engine/mock_payload_state.h"
56 #include "update_engine/omaha_request_builder_xml.h"
57 #include "update_engine/omaha_request_params.h"
58 #include "update_engine/omaha_utils.h"
59 #include "update_engine/update_manager/rollback_prefs.h"
60
61 using base::Time;
62 using base::TimeDelta;
63 using chromeos_update_manager::kRollforwardInfinity;
64 using std::pair;
65 using std::string;
66 using std::vector;
67 using testing::_;
68 using testing::AllOf;
69 using testing::AnyNumber;
70 using testing::DoAll;
71 using testing::Ge;
72 using testing::Le;
73 using testing::NiceMock;
74 using testing::Return;
75 using testing::ReturnPointee;
76 using testing::ReturnRef;
77 using testing::SaveArg;
78 using testing::SetArgPointee;
79 using testing::StrictMock;
80
81 namespace {
82
83 static_assert(kRollforwardInfinity == 0xfffffffe,
84 "Don't change the value of kRollforward infinity unless its "
85 "size has been changed in firmware.");
86
87 const char kCurrentVersion[] = "0.1.0.0";
88 const char kTestAppId[] = "test-app-id";
89 const char kTestAppId2[] = "test-app2-id";
90 const char kTestAppIdSkipUpdatecheck[] = "test-app-id-skip-updatecheck";
91 const char kDlcId1[] = "dlc-id-1";
92 const char kDlcId2[] = "dlc-id-2";
93
94 // This is a helper struct to allow unit tests build an update response with the
95 // values they care about.
96 struct FakeUpdateResponse {
GetRollbackVersionAttributes__anonebf7ac180111::FakeUpdateResponse97 string GetRollbackVersionAttributes() const {
98 string num_milestones;
99 num_milestones = base::NumberToString(rollback_allowed_milestones);
100 const string rollback_version =
101 " _firmware_version_" + num_milestones + "=\"" +
102 past_rollback_key_version.first + "\"" + " _kernel_version_" +
103 num_milestones + "=\"" + past_rollback_key_version.second + "\"";
104
105 return (rollback ? " _rollback=\"true\"" : "") + rollback_version +
106 (!rollback_firmware_version.empty()
107 ? " _firmware_version=\"" + rollback_firmware_version + "\""
108 : "") +
109 (!rollback_kernel_version.empty()
110 ? " _kernel_version=\"" + rollback_kernel_version + "\""
111 : "");
112 }
113
GetNoUpdateResponse__anonebf7ac180111::FakeUpdateResponse114 string GetNoUpdateResponse() const {
115 string entity_str;
116 if (include_entity)
117 entity_str = "<!DOCTYPE response [<!ENTITY CrOS \"ChromeOS\">]>";
118 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + entity_str +
119 "<response protocol=\"3.0\">"
120 "<daystart elapsed_seconds=\"100\"/>"
121 "<app appid=\"" +
122 app_id + "\" " +
123 (include_cohorts
124 ? "cohort=\"" + cohort + "\" cohorthint=\"" + cohorthint +
125 "\" cohortname=\"" + cohortname + "\" "
126 : "") +
127 " status=\"ok\">"
128 "<ping status=\"ok\"/>"
129 "<updatecheck status=\"noupdate\"/></app>" +
130 (multi_app_no_update
131 ? "<app appid=\"" + app_id2 +
132 "\"><updatecheck status=\"noupdate\"/></app>"
133 : "") +
134 "</response>";
135 }
136
GetUpdateResponse__anonebf7ac180111::FakeUpdateResponse137 string GetUpdateResponse() const {
138 chromeos_update_engine::OmahaRequestParams request_params{nullptr};
139 request_params.set_app_id(app_id);
140 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
141 "protocol=\"3.0\">"
142 "<daystart elapsed_seconds=\"100\"" +
143 (elapsed_days.empty() ? ""
144 : (" elapsed_days=\"" + elapsed_days + "\"")) +
145 "/>"
146 "<app appid=\"" +
147 app_id + "\" " +
148 (include_cohorts
149 ? "cohort=\"" + cohort + "\" cohorthint=\"" + cohorthint +
150 "\" cohortname=\"" + cohortname + "\" "
151 : "") +
152 " status=\"ok\">"
153 "<ping status=\"ok\"/><updatecheck status=\"ok\"" +
154 GetRollbackVersionAttributes() + ">" + "<urls><url codebase=\"" +
155 codebase +
156 "\"/></urls>"
157 "<manifest version=\"" +
158 version +
159 "\">"
160 "<packages><package hash=\"not-used\" name=\"" +
161 filename + "\" size=\"" + base::NumberToString(size) +
162 "\" hash_sha256=\"" + hash + "\"/>" +
163 (multi_package ? "<package name=\"package2\" size=\"222\" "
164 "hash_sha256=\"hash2\"/>"
165 : "") +
166 "</packages>"
167 "<actions><action event=\"postinstall\" MetadataSize=\"11" +
168 (multi_package ? ":22" : "") + "\" MoreInfo=\"" + more_info_url +
169 "\" Prompt=\"" + prompt +
170 "\" "
171 "IsDeltaPayload=\"true" +
172 (multi_package ? ":false" : "") +
173 "\" "
174 "MaxDaysToScatter=\"" +
175 max_days_to_scatter +
176 "\" "
177 "sha256=\"not-used\" " +
178 (deadline.empty() ? "" : ("deadline=\"" + deadline + "\" ")) +
179 (disable_p2p_for_downloading ? "DisableP2PForDownloading=\"true\" "
180 : "") +
181 (disable_p2p_for_sharing ? "DisableP2PForSharing=\"true\" " : "") +
182 (powerwash ? "Powerwash=\"true\" " : "") +
183 "/></actions></manifest></updatecheck></app>" +
184 (multi_app
185 ? "<app appid=\"" + app_id2 + "\"" +
186 (include_cohorts ? " cohort=\"cohort2\"" : "") +
187 "><updatecheck status=\"ok\"><urls><url codebase=\"" +
188 codebase2 + "\"/></urls><manifest version=\"" + version2 +
189 "\"><packages>"
190 "<package name=\"package3\" size=\"333\" "
191 "hash_sha256=\"hash3\"/></packages>"
192 "<actions><action event=\"postinstall\" " +
193 (multi_app_self_update
194 ? "noupdate=\"true\" IsDeltaPayload=\"true\" "
195 : "IsDeltaPayload=\"false\" ") +
196 "MetadataSize=\"33\"/></actions>"
197 "</manifest></updatecheck></app>"
198 : "") +
199 (multi_app_no_update
200 ? "<app><updatecheck status=\"noupdate\"/></app>"
201 : "") +
202 (multi_app_skip_updatecheck
203 ? "<app appid=\"" + app_id_skip_updatecheck + "\"></app>"
204 : "") +
205 (dlc_app_update
206 ? "<app appid=\"" + request_params.GetDlcAppId(kDlcId1) +
207 "\" status=\"ok\">"
208 "<updatecheck status=\"ok\"><urls><url codebase=\"" +
209 codebase + "\"/><url codebase=\"" + codebase2 +
210 "\"/></urls><manifest version=\"" + version +
211 "\"><packages><package name=\"package3\" size=\"333\" "
212 "hash_sha256=\"hash3\"/></packages><actions>"
213 "<action event=\"install\" run=\".signed\"/>"
214 "<action event=\"postinstall\" MetadataSize=\"33\"/>"
215 "</actions></manifest></updatecheck></app>"
216 : "") +
217 (dlc_app_no_update
218 ? "<app appid=\"" + request_params.GetDlcAppId(kDlcId2) +
219 "\"><updatecheck status=\"noupdate\"/></app>"
220 : "") +
221 "</response>";
222 }
223
224 // Return the payload URL, which is split in two fields in the XML response.
GetPayloadUrl__anonebf7ac180111::FakeUpdateResponse225 string GetPayloadUrl() { return codebase + filename; }
226
227 string app_id = kTestAppId;
228 string app_id2 = kTestAppId2;
229 string app_id_skip_updatecheck = kTestAppIdSkipUpdatecheck;
230 string current_version = kCurrentVersion;
231 string version = "1.2.3.4";
232 string version2 = "2.3.4.5";
233 string more_info_url = "http://more/info";
234 string prompt = "true";
235 string codebase = "http://code/base/";
236 string codebase2 = "http://code/base/2/";
237 string filename = "file.signed";
238 string hash = "4841534831323334";
239 uint64_t size = 123;
240 string deadline = "";
241 string max_days_to_scatter = "7";
242 string elapsed_days = "42";
243
244 // P2P setting defaults to allowed.
245 bool disable_p2p_for_downloading = false;
246 bool disable_p2p_for_sharing = false;
247
248 bool powerwash = false;
249
250 // Omaha cohorts settings.
251 bool include_cohorts = false;
252 string cohort = "";
253 string cohorthint = "";
254 string cohortname = "";
255
256 // Whether to include the CrOS <!ENTITY> in the XML response.
257 bool include_entity = false;
258
259 // Whether to include more than one app.
260 bool multi_app = false;
261 // Whether to include an app with noupdate="true".
262 bool multi_app_self_update = false;
263 // Whether to include an additional app with status="noupdate".
264 bool multi_app_no_update = false;
265 // Whether to include an additional app with no updatecheck tag.
266 bool multi_app_skip_updatecheck = false;
267 // Whether to include more than one package in an app.
268 bool multi_package = false;
269 // Whether to include a DLC app with updatecheck tag.
270 bool dlc_app_update = false;
271 // Whether to include a DLC app with no updatecheck tag.
272 bool dlc_app_no_update = false;
273
274 // Whether the payload is a rollback.
275 bool rollback = false;
276 // The verified boot firmware key version for the rollback image.
277 string rollback_firmware_version = "";
278 // The verified boot kernel key version for the rollback image.
279 string rollback_kernel_version = "";
280 // The number of milestones back that the verified boot key version has been
281 // supplied.
282 uint32_t rollback_allowed_milestones = 0;
283 // The verified boot key version for the
284 // |current - rollback_allowed_milestones| most recent release.
285 // The pair contains <firmware_key_version, kernel_key_version> each
286 // of which is in the form "key_version.version".
287 pair<string, string> past_rollback_key_version;
288 };
289
290 } // namespace
291
292 namespace chromeos_update_engine {
293
294 class OmahaRequestActionTestProcessorDelegate : public ActionProcessorDelegate {
295 public:
OmahaRequestActionTestProcessorDelegate()296 OmahaRequestActionTestProcessorDelegate()
297 : expected_code_(ErrorCode::kSuccess),
298 interactive_(false),
299 test_http_fetcher_headers_(false) {}
300 ~OmahaRequestActionTestProcessorDelegate() override = default;
301
ProcessingDone(const ActionProcessor * processor,ErrorCode code)302 void ProcessingDone(const ActionProcessor* processor,
303 ErrorCode code) override {
304 brillo::MessageLoop::current()->BreakLoop();
305 }
306
ActionCompleted(ActionProcessor * processor,AbstractAction * action,ErrorCode code)307 void ActionCompleted(ActionProcessor* processor,
308 AbstractAction* action,
309 ErrorCode code) override {
310 // Make sure actions always succeed.
311 if (action->Type() == OmahaRequestAction::StaticType()) {
312 EXPECT_EQ(expected_code_, code);
313 // Check that the headers were set in the fetcher during the action. Note
314 // that we set this request as "interactive".
315 auto fetcher = static_cast<const MockHttpFetcher*>(
316 static_cast<OmahaRequestAction*>(action)->http_fetcher_.get());
317
318 if (test_http_fetcher_headers_) {
319 EXPECT_EQ(interactive_ ? "fg" : "bg",
320 fetcher->GetHeader("X-Goog-Update-Interactivity"));
321 EXPECT_EQ(kTestAppId, fetcher->GetHeader("X-Goog-Update-AppId"));
322 EXPECT_NE("", fetcher->GetHeader("X-Goog-Update-Updater"));
323 }
324 post_data_ = fetcher->post_data();
325 } else if (action->Type() ==
326 ObjectCollectorAction<OmahaResponse>::StaticType()) {
327 EXPECT_EQ(ErrorCode::kSuccess, code);
328 auto collector_action =
329 static_cast<ObjectCollectorAction<OmahaResponse>*>(action);
330 omaha_response_.reset(new OmahaResponse(collector_action->object()));
331 EXPECT_TRUE(omaha_response_);
332 } else {
333 EXPECT_EQ(ErrorCode::kSuccess, code);
334 }
335 }
336 ErrorCode expected_code_;
337 brillo::Blob post_data_;
338 bool interactive_;
339 bool test_http_fetcher_headers_;
340 std::unique_ptr<OmahaResponse> omaha_response_;
341 };
342
343 struct TestUpdateCheckParams {
344 string http_response;
345 int fail_http_response_code;
346 bool ping_only;
347 bool is_consumer_device;
348 int rollback_allowed_milestones;
349 bool is_policy_loaded;
350 ErrorCode expected_code;
351 metrics::CheckResult expected_check_result;
352 metrics::CheckReaction expected_check_reaction;
353 metrics::DownloadErrorCode expected_download_error_code;
354 string session_id;
355 };
356
357 class OmahaRequestActionTest : public ::testing::Test {
358 protected:
SetUp()359 void SetUp() override {
360 request_params_.set_os_sp("service_pack");
361 request_params_.set_os_board("x86-generic");
362 request_params_.set_app_id(kTestAppId);
363 request_params_.set_app_version(kCurrentVersion);
364 request_params_.set_app_lang("en-US");
365 request_params_.set_current_channel("unittest");
366 request_params_.set_target_channel("unittest");
367 request_params_.set_hwid("OEM MODEL 09235 7471");
368 request_params_.set_fw_version("ChromeOSFirmware.1.0");
369 request_params_.set_ec_version("0X0A1");
370 request_params_.set_delta_okay(true);
371 request_params_.set_interactive(false);
372 request_params_.set_update_url("http://url");
373 request_params_.set_target_version_prefix("");
374 request_params_.set_rollback_allowed(false);
375 request_params_.set_is_powerwash_allowed(false);
376 request_params_.set_is_install(false);
377 request_params_.set_dlc_apps_params({});
378
379 fake_system_state_.set_request_params(&request_params_);
380 fake_system_state_.set_prefs(&fake_prefs_);
381
382 // Setting the default update check params. Lookup |TestUpdateCheck()|.
383 tuc_params_ = {
384 .http_response = "",
385 .fail_http_response_code = -1,
386 .ping_only = false,
387 .is_consumer_device = true,
388 .rollback_allowed_milestones = 0,
389 .is_policy_loaded = false,
390 .expected_code = ErrorCode::kSuccess,
391 .expected_check_result = metrics::CheckResult::kUpdateAvailable,
392 .expected_check_reaction = metrics::CheckReaction::kUpdating,
393 .expected_download_error_code = metrics::DownloadErrorCode::kUnset,
394 };
395
396 ON_CALL(*fake_system_state_.mock_update_attempter(), GetExcluder())
397 .WillByDefault(Return(&mock_excluder_));
398 }
399
400 // This function uses the parameters in |tuc_params_| to do an update check.
401 // It will fill out |post_str| with the result data and |response| with
402 // |OmahaResponse|. Returns true iff an output response was obtained from the
403 // |OmahaRequestAction|. If |fail_http_response_code| is non-negative, the
404 // transfer will fail with that code. |ping_only| is passed through to the
405 // |OmahaRequestAction| constructor.
406 //
407 // The |expected_check_result|, |expected_check_reaction| and
408 // |expected_error_code| parameters are for checking expectations about
409 // reporting UpdateEngine.Check.{Result,Reaction,DownloadError} UMA
410 // statistics. Use the appropriate ::kUnset value to specify that the given
411 // metric should not be reported.
412 bool TestUpdateCheck();
413
414 // Tests events using |event| and |https_response|. It will fill up |post_str|
415 // with the result data.
416 void TestEvent(OmahaEvent* event, const string& http_response);
417
418 // Runs and checks a ping test. |ping_only| indicates whether it should send
419 // only a ping or also an updatecheck.
420 void PingTest(bool ping_only);
421
422 // InstallDate test helper function.
423 bool InstallDateParseHelper(const string& elapsed_days,
424 OmahaResponse* response);
425
426 // P2P test helper function.
427 void P2PTest(bool initial_allow_p2p_for_downloading,
428 bool initial_allow_p2p_for_sharing,
429 bool omaha_disable_p2p_for_downloading,
430 bool omaha_disable_p2p_for_sharing,
431 bool payload_state_allow_p2p_attempt,
432 bool expect_p2p_client_lookup,
433 const string& p2p_client_result_url,
434 bool expected_allow_p2p_for_downloading,
435 bool expected_allow_p2p_for_sharing,
436 const string& expected_p2p_url);
437
438 StrictMock<MockExcluder> mock_excluder_;
439 FakeSystemState fake_system_state_;
440 FakeUpdateResponse fake_update_response_;
441 // Used by all tests.
442 OmahaRequestParams request_params_{&fake_system_state_};
443
444 FakePrefs fake_prefs_;
445
446 OmahaRequestActionTestProcessorDelegate delegate_;
447
448 bool test_http_fetcher_headers_{false};
449
450 TestUpdateCheckParams tuc_params_;
451
452 // TODO(ahassani): Add trailing _ to these two variables.
453 OmahaResponse response;
454 string post_str;
455 };
456
457 class OmahaRequestActionDlcPingTest : public OmahaRequestActionTest {
458 protected:
SetUp()459 void SetUp() override {
460 OmahaRequestActionTest::SetUp();
461 dlc_id_ = "dlc0";
462 active_key_ = PrefsInterface::CreateSubKey(
463 {kDlcPrefsSubDir, dlc_id_, kPrefsPingActive});
464 last_active_key_ = PrefsInterface::CreateSubKey(
465 {kDlcPrefsSubDir, dlc_id_, kPrefsPingLastActive});
466 last_rollcall_key_ = PrefsInterface::CreateSubKey(
467 {kDlcPrefsSubDir, dlc_id_, kPrefsPingLastRollcall});
468
469 tuc_params_.http_response =
470 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
471 "protocol=\"3.0\"><daystart elapsed_days=\"4763\" "
472 "elapsed_seconds=\"36540\"/><app appid=\"test-app-id\" status=\"ok\">\""
473 "<updatecheck status=\"noupdate\"/></app><app "
474 "appid=\"test-app-id_dlc0\" "
475 "status=\"ok\"><ping status=\"ok\"/><updatecheck status=\"noupdate\"/>"
476 "</app></response>";
477 tuc_params_.expected_check_result =
478 metrics::CheckResult::kNoUpdateAvailable;
479 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
480 }
481
482 std::string dlc_id_;
483 std::string active_key_;
484 std::string last_active_key_;
485 std::string last_rollcall_key_;
486 };
TestUpdateCheck()487 bool OmahaRequestActionTest::TestUpdateCheck() {
488 brillo::FakeMessageLoop loop(nullptr);
489 loop.SetAsCurrent();
490 auto fetcher =
491 std::make_unique<MockHttpFetcher>(tuc_params_.http_response.data(),
492 tuc_params_.http_response.size(),
493 nullptr);
494 if (tuc_params_.fail_http_response_code >= 0) {
495 fetcher->FailTransfer(tuc_params_.fail_http_response_code);
496 }
497 // This ensures the tests didn't forget to update fake_system_state_ if they
498 // are not using the default request_params_.
499 EXPECT_EQ(&request_params_, fake_system_state_.request_params());
500
501 auto omaha_request_action =
502 std::make_unique<OmahaRequestAction>(&fake_system_state_,
503 nullptr,
504 std::move(fetcher),
505 tuc_params_.ping_only,
506 tuc_params_.session_id);
507
508 auto mock_policy_provider =
509 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
510 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
511 .WillRepeatedly(Return(tuc_params_.is_consumer_device));
512
513 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
514 .WillRepeatedly(Return(tuc_params_.is_policy_loaded));
515
516 const policy::MockDevicePolicy device_policy;
517 const bool get_allowed_milestone_succeeds =
518 tuc_params_.rollback_allowed_milestones >= 0;
519 EXPECT_CALL(device_policy, GetRollbackAllowedMilestones(_))
520 .WillRepeatedly(
521 DoAll(SetArgPointee<0>(tuc_params_.rollback_allowed_milestones),
522 Return(get_allowed_milestone_succeeds)));
523
524 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
525 .WillRepeatedly(ReturnRef(device_policy));
526 omaha_request_action->policy_provider_ = std::move(mock_policy_provider);
527
528 delegate_.expected_code_ = tuc_params_.expected_code;
529 delegate_.interactive_ = request_params_.interactive();
530 delegate_.test_http_fetcher_headers_ = test_http_fetcher_headers_;
531 ActionProcessor processor;
532 processor.set_delegate(&delegate_);
533
534 auto collector_action =
535 std::make_unique<ObjectCollectorAction<OmahaResponse>>();
536 BondActions(omaha_request_action.get(), collector_action.get());
537 processor.EnqueueAction(std::move(omaha_request_action));
538 processor.EnqueueAction(std::move(collector_action));
539
540 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
541 ReportUpdateCheckMetrics(_, _, _, _))
542 .Times(AnyNumber());
543
544 EXPECT_CALL(
545 *fake_system_state_.mock_metrics_reporter(),
546 ReportUpdateCheckMetrics(_,
547 tuc_params_.expected_check_result,
548 tuc_params_.expected_check_reaction,
549 tuc_params_.expected_download_error_code))
550 .Times(tuc_params_.ping_only ? 0 : 1);
551
552 loop.PostTask(base::Bind(
553 [](ActionProcessor* processor) { processor->StartProcessing(); },
554 base::Unretained(&processor)));
555 loop.Run();
556 EXPECT_FALSE(loop.PendingTasks());
557 if (delegate_.omaha_response_)
558 response = *delegate_.omaha_response_;
559 post_str = string(delegate_.post_data_.begin(), delegate_.post_data_.end());
560 return delegate_.omaha_response_ != nullptr;
561 }
562
563 // Tests Event requests -- they should always succeed. |out_post_data| may be
564 // null; if non-null, the post-data received by the mock HttpFetcher is
565 // returned.
TestEvent(OmahaEvent * event,const string & http_response)566 void OmahaRequestActionTest::TestEvent(OmahaEvent* event,
567 const string& http_response) {
568 brillo::FakeMessageLoop loop(nullptr);
569 loop.SetAsCurrent();
570
571 auto action = std::make_unique<OmahaRequestAction>(
572 &fake_system_state_,
573 event,
574 std::make_unique<MockHttpFetcher>(
575 http_response.data(), http_response.size(), nullptr),
576 false,
577 "");
578 ActionProcessor processor;
579 processor.set_delegate(&delegate_);
580 processor.EnqueueAction(std::move(action));
581
582 loop.PostTask(base::Bind(
583 [](ActionProcessor* processor) { processor->StartProcessing(); },
584 base::Unretained(&processor)));
585 loop.Run();
586 EXPECT_FALSE(loop.PendingTasks());
587
588 post_str = string(delegate_.post_data_.begin(), delegate_.post_data_.end());
589 }
590
TEST_F(OmahaRequestActionTest,RejectEntities)591 TEST_F(OmahaRequestActionTest, RejectEntities) {
592 fake_update_response_.include_entity = true;
593 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
594 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
595 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
596 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
597
598 ASSERT_FALSE(TestUpdateCheck());
599 EXPECT_FALSE(response.update_exists);
600 }
601
TEST_F(OmahaRequestActionTest,NoUpdateTest)602 TEST_F(OmahaRequestActionTest, NoUpdateTest) {
603 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
604 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
605 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
606
607 ASSERT_TRUE(TestUpdateCheck());
608 EXPECT_FALSE(response.update_exists);
609 }
610
TEST_F(OmahaRequestActionTest,MultiAppNoUpdateTest)611 TEST_F(OmahaRequestActionTest, MultiAppNoUpdateTest) {
612 fake_update_response_.multi_app_no_update = true;
613 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
614 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
615 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
616
617 ASSERT_TRUE(TestUpdateCheck());
618 EXPECT_FALSE(response.update_exists);
619 }
620
TEST_F(OmahaRequestActionTest,MultiAppNoPartialUpdateTest)621 TEST_F(OmahaRequestActionTest, MultiAppNoPartialUpdateTest) {
622 fake_update_response_.multi_app_no_update = true;
623 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
624 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
625 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
626
627 ASSERT_TRUE(TestUpdateCheck());
628 EXPECT_FALSE(response.update_exists);
629 }
630
TEST_F(OmahaRequestActionTest,NoSelfUpdateTest)631 TEST_F(OmahaRequestActionTest, NoSelfUpdateTest) {
632 tuc_params_.http_response =
633 "<response><app><updatecheck status=\"ok\"><manifest><actions><action "
634 "event=\"postinstall\" noupdate=\"true\"/></actions>"
635 "</manifest></updatecheck></app></response>";
636 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
637 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
638
639 ASSERT_TRUE(TestUpdateCheck());
640 EXPECT_FALSE(response.update_exists);
641 }
642
643 // Test that all the values in the response are parsed in a normal update
644 // response.
TEST_F(OmahaRequestActionTest,ValidUpdateTest)645 TEST_F(OmahaRequestActionTest, ValidUpdateTest) {
646 fake_update_response_.deadline = "20101020";
647 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
648
649 ASSERT_TRUE(TestUpdateCheck());
650
651 EXPECT_TRUE(response.update_exists);
652 EXPECT_EQ(fake_update_response_.version, response.version);
653 EXPECT_EQ("", response.system_version);
654 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
655 response.packages[0].payload_urls[0]);
656 EXPECT_EQ(fake_update_response_.more_info_url, response.more_info_url);
657 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
658 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
659 EXPECT_EQ(true, response.packages[0].is_delta);
660 EXPECT_EQ(fake_update_response_.prompt == "true", response.prompt);
661 EXPECT_EQ(fake_update_response_.deadline, response.deadline);
662 EXPECT_FALSE(response.powerwash_required);
663 // Omaha cohort attributes are not set in the response, so they should not be
664 // persisted.
665 EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohort));
666 EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohortHint));
667 EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohortName));
668 }
669
TEST_F(OmahaRequestActionTest,MultiPackageUpdateTest)670 TEST_F(OmahaRequestActionTest, MultiPackageUpdateTest) {
671 fake_update_response_.multi_package = true;
672 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
673
674 ASSERT_TRUE(TestUpdateCheck());
675
676 EXPECT_TRUE(response.update_exists);
677 EXPECT_EQ(fake_update_response_.version, response.version);
678 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
679 response.packages[0].payload_urls[0]);
680 EXPECT_EQ(fake_update_response_.codebase + "package2",
681 response.packages[1].payload_urls[0]);
682 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
683 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
684 EXPECT_EQ(true, response.packages[0].is_delta);
685 EXPECT_EQ(11u, response.packages[0].metadata_size);
686 ASSERT_EQ(2u, response.packages.size());
687 EXPECT_EQ(string("hash2"), response.packages[1].hash);
688 EXPECT_EQ(222u, response.packages[1].size);
689 EXPECT_EQ(22u, response.packages[1].metadata_size);
690 EXPECT_EQ(false, response.packages[1].is_delta);
691 }
692
TEST_F(OmahaRequestActionTest,MultiAppUpdateTest)693 TEST_F(OmahaRequestActionTest, MultiAppUpdateTest) {
694 fake_update_response_.multi_app = true;
695 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
696
697 ASSERT_TRUE(TestUpdateCheck());
698
699 EXPECT_TRUE(response.update_exists);
700 EXPECT_EQ(fake_update_response_.version, response.version);
701 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
702 response.packages[0].payload_urls[0]);
703 EXPECT_EQ(fake_update_response_.codebase2 + "package3",
704 response.packages[1].payload_urls[0]);
705 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
706 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
707 EXPECT_EQ(11u, response.packages[0].metadata_size);
708 EXPECT_EQ(true, response.packages[0].is_delta);
709 ASSERT_EQ(2u, response.packages.size());
710 EXPECT_EQ(string("hash3"), response.packages[1].hash);
711 EXPECT_EQ(333u, response.packages[1].size);
712 EXPECT_EQ(33u, response.packages[1].metadata_size);
713 EXPECT_EQ(false, response.packages[1].is_delta);
714 }
715
TEST_F(OmahaRequestActionTest,MultiAppAndSystemUpdateTest)716 TEST_F(OmahaRequestActionTest, MultiAppAndSystemUpdateTest) {
717 fake_update_response_.multi_app = true;
718 // Trigger the lining up of the app and system versions.
719 request_params_.set_system_app_id(fake_update_response_.app_id2);
720 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
721
722 ASSERT_TRUE(TestUpdateCheck());
723
724 EXPECT_TRUE(response.update_exists);
725 EXPECT_EQ(fake_update_response_.version, response.version);
726 EXPECT_EQ(fake_update_response_.version2, response.system_version);
727 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
728 response.packages[0].payload_urls[0]);
729 EXPECT_EQ(fake_update_response_.codebase2 + "package3",
730 response.packages[1].payload_urls[0]);
731 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
732 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
733 EXPECT_EQ(11u, response.packages[0].metadata_size);
734 EXPECT_EQ(true, response.packages[0].is_delta);
735 ASSERT_EQ(2u, response.packages.size());
736 EXPECT_EQ(string("hash3"), response.packages[1].hash);
737 EXPECT_EQ(333u, response.packages[1].size);
738 EXPECT_EQ(33u, response.packages[1].metadata_size);
739 EXPECT_EQ(false, response.packages[1].is_delta);
740 }
741
TEST_F(OmahaRequestActionTest,MultiAppPartialUpdateTest)742 TEST_F(OmahaRequestActionTest, MultiAppPartialUpdateTest) {
743 fake_update_response_.multi_app = true;
744 fake_update_response_.multi_app_self_update = true;
745 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
746
747 ASSERT_TRUE(TestUpdateCheck());
748
749 EXPECT_TRUE(response.update_exists);
750 EXPECT_EQ(fake_update_response_.version, response.version);
751 EXPECT_EQ("", response.system_version);
752 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
753 response.packages[0].payload_urls[0]);
754 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
755 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
756 EXPECT_EQ(11u, response.packages[0].metadata_size);
757 ASSERT_EQ(2u, response.packages.size());
758 EXPECT_EQ(string("hash3"), response.packages[1].hash);
759 EXPECT_EQ(333u, response.packages[1].size);
760 EXPECT_EQ(33u, response.packages[1].metadata_size);
761 EXPECT_EQ(true, response.packages[1].is_delta);
762 }
763
TEST_F(OmahaRequestActionTest,MultiAppMultiPackageUpdateTest)764 TEST_F(OmahaRequestActionTest, MultiAppMultiPackageUpdateTest) {
765 fake_update_response_.multi_app = true;
766 fake_update_response_.multi_package = true;
767 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
768
769 ASSERT_TRUE(TestUpdateCheck());
770
771 EXPECT_TRUE(response.update_exists);
772 EXPECT_EQ(fake_update_response_.version, response.version);
773 EXPECT_EQ("", response.system_version);
774 EXPECT_EQ(fake_update_response_.GetPayloadUrl(),
775 response.packages[0].payload_urls[0]);
776 EXPECT_EQ(fake_update_response_.codebase + "package2",
777 response.packages[1].payload_urls[0]);
778 EXPECT_EQ(fake_update_response_.codebase2 + "package3",
779 response.packages[2].payload_urls[0]);
780 EXPECT_EQ(fake_update_response_.hash, response.packages[0].hash);
781 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
782 EXPECT_EQ(11u, response.packages[0].metadata_size);
783 EXPECT_EQ(true, response.packages[0].is_delta);
784 ASSERT_EQ(3u, response.packages.size());
785 EXPECT_EQ(string("hash2"), response.packages[1].hash);
786 EXPECT_EQ(222u, response.packages[1].size);
787 EXPECT_EQ(22u, response.packages[1].metadata_size);
788 EXPECT_EQ(false, response.packages[1].is_delta);
789 EXPECT_EQ(string("hash3"), response.packages[2].hash);
790 EXPECT_EQ(333u, response.packages[2].size);
791 EXPECT_EQ(33u, response.packages[2].metadata_size);
792 EXPECT_EQ(false, response.packages[2].is_delta);
793 }
794
TEST_F(OmahaRequestActionTest,PowerwashTest)795 TEST_F(OmahaRequestActionTest, PowerwashTest) {
796 fake_update_response_.powerwash = true;
797 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
798
799 ASSERT_TRUE(TestUpdateCheck());
800
801 EXPECT_TRUE(response.update_exists);
802 EXPECT_TRUE(response.powerwash_required);
803 }
804
TEST_F(OmahaRequestActionTest,ExtraHeadersSentInteractiveTest)805 TEST_F(OmahaRequestActionTest, ExtraHeadersSentInteractiveTest) {
806 request_params_.set_interactive(true);
807 test_http_fetcher_headers_ = true;
808 tuc_params_.http_response = "invalid xml>";
809 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
810 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
811 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
812
813 ASSERT_FALSE(TestUpdateCheck());
814
815 EXPECT_FALSE(response.update_exists);
816 }
817
TEST_F(OmahaRequestActionTest,ExtraHeadersSentNoInteractiveTest)818 TEST_F(OmahaRequestActionTest, ExtraHeadersSentNoInteractiveTest) {
819 request_params_.set_interactive(false);
820 test_http_fetcher_headers_ = true;
821 tuc_params_.http_response = "invalid xml>";
822 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
823 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
824 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
825
826 ASSERT_FALSE(TestUpdateCheck());
827
828 EXPECT_FALSE(response.update_exists);
829 }
830
TEST_F(OmahaRequestActionTest,ValidUpdateBlockedByConnection)831 TEST_F(OmahaRequestActionTest, ValidUpdateBlockedByConnection) {
832 // Set up a connection manager that doesn't allow a valid update over
833 // the current ethernet connection.
834 MockConnectionManager mock_cm;
835 fake_system_state_.set_connection_manager(&mock_cm);
836
837 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
838 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kEthernet),
839 SetArgPointee<1>(ConnectionTethering::kUnknown),
840 Return(true)));
841 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kEthernet, _))
842 .WillRepeatedly(Return(false));
843
844 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
845 tuc_params_.expected_code = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
846 tuc_params_.expected_check_reaction = metrics::CheckReaction::kIgnored;
847
848 ASSERT_FALSE(TestUpdateCheck());
849
850 EXPECT_FALSE(response.update_exists);
851 }
852
TEST_F(OmahaRequestActionTest,ValidUpdateOverCellularAllowedByDevicePolicy)853 TEST_F(OmahaRequestActionTest, ValidUpdateOverCellularAllowedByDevicePolicy) {
854 // This test tests that update over cellular is allowed as device policy
855 // says yes.
856 MockConnectionManager mock_cm;
857 fake_system_state_.set_connection_manager(&mock_cm);
858
859 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
860 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
861 SetArgPointee<1>(ConnectionTethering::kUnknown),
862 Return(true)));
863 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
864 .WillRepeatedly(Return(true));
865 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kCellular, _))
866 .WillRepeatedly(Return(true));
867
868 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
869
870 ASSERT_TRUE(TestUpdateCheck());
871
872 EXPECT_TRUE(response.update_exists);
873 }
874
TEST_F(OmahaRequestActionTest,ValidUpdateOverCellularBlockedByDevicePolicy)875 TEST_F(OmahaRequestActionTest, ValidUpdateOverCellularBlockedByDevicePolicy) {
876 // This test tests that update over cellular is blocked as device policy
877 // says no.
878 MockConnectionManager mock_cm;
879 fake_system_state_.set_connection_manager(&mock_cm);
880
881 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
882 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
883 SetArgPointee<1>(ConnectionTethering::kUnknown),
884 Return(true)));
885 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
886 .WillRepeatedly(Return(true));
887 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kCellular, _))
888 .WillRepeatedly(Return(false));
889
890 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
891 tuc_params_.expected_code = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
892 tuc_params_.expected_check_reaction = metrics::CheckReaction::kIgnored;
893
894 ASSERT_FALSE(TestUpdateCheck());
895
896 EXPECT_FALSE(response.update_exists);
897 }
898
TEST_F(OmahaRequestActionTest,ValidUpdateOverCellularAllowedByUserPermissionTrue)899 TEST_F(OmahaRequestActionTest,
900 ValidUpdateOverCellularAllowedByUserPermissionTrue) {
901 // This test tests that, when device policy is not set, update over cellular
902 // is allowed as permission for update over cellular is set to true.
903 MockConnectionManager mock_cm;
904 fake_prefs_.SetBoolean(kPrefsUpdateOverCellularPermission, true);
905 fake_system_state_.set_connection_manager(&mock_cm);
906
907 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
908 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
909 SetArgPointee<1>(ConnectionTethering::kUnknown),
910 Return(true)));
911 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
912 .WillRepeatedly(Return(false));
913 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kCellular, _))
914 .WillRepeatedly(Return(true));
915
916 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
917
918 ASSERT_TRUE(TestUpdateCheck());
919
920 EXPECT_TRUE(response.update_exists);
921 }
922
TEST_F(OmahaRequestActionTest,ValidUpdateOverCellularBlockedByUpdateTargetNotMatch)923 TEST_F(OmahaRequestActionTest,
924 ValidUpdateOverCellularBlockedByUpdateTargetNotMatch) {
925 // This test tests that, when device policy is not set and permission for
926 // update over cellular is set to false or does not exist, update over
927 // cellular is blocked as update target does not match the omaha response.
928 MockConnectionManager mock_cm;
929 // A version different from the version in omaha response.
930 string diff_version = "99.99.99";
931 // A size different from the size in omaha response.
932 int64_t diff_size = 999;
933
934 fake_prefs_.SetString(kPrefsUpdateOverCellularTargetVersion, diff_version);
935 fake_prefs_.SetInt64(kPrefsUpdateOverCellularTargetSize, diff_size);
936 // This test tests cellular (3G) being the only connection type being allowed.
937 fake_system_state_.set_connection_manager(&mock_cm);
938
939 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
940 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
941 SetArgPointee<1>(ConnectionTethering::kUnknown),
942 Return(true)));
943 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
944 .WillRepeatedly(Return(false));
945 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kCellular, _))
946 .WillRepeatedly(Return(true));
947
948 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
949 tuc_params_.expected_code = ErrorCode::kOmahaUpdateIgnoredOverCellular;
950 tuc_params_.expected_check_reaction = metrics::CheckReaction::kIgnored;
951
952 ASSERT_FALSE(TestUpdateCheck());
953
954 EXPECT_FALSE(response.update_exists);
955 }
956
TEST_F(OmahaRequestActionTest,ValidUpdateOverCellularAllowedByUpdateTargetMatch)957 TEST_F(OmahaRequestActionTest,
958 ValidUpdateOverCellularAllowedByUpdateTargetMatch) {
959 // This test tests that, when device policy is not set and permission for
960 // update over cellular is set to false or does not exist, update over
961 // cellular is allowed as update target matches the omaha response.
962 MockConnectionManager mock_cm;
963 // A version same as the version in omaha response.
964 string new_version = fake_update_response_.version;
965 // A size same as the size in omaha response.
966 int64_t new_size = fake_update_response_.size;
967
968 fake_prefs_.SetString(kPrefsUpdateOverCellularTargetVersion, new_version);
969 fake_prefs_.SetInt64(kPrefsUpdateOverCellularTargetSize, new_size);
970 fake_system_state_.set_connection_manager(&mock_cm);
971
972 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
973 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
974 SetArgPointee<1>(ConnectionTethering::kUnknown),
975 Return(true)));
976 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
977 .WillRepeatedly(Return(false));
978 EXPECT_CALL(mock_cm, IsUpdateAllowedOver(ConnectionType::kCellular, _))
979 .WillRepeatedly(Return(true));
980
981 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
982
983 ASSERT_TRUE(TestUpdateCheck());
984
985 EXPECT_TRUE(response.update_exists);
986 }
987
TEST_F(OmahaRequestActionTest,ValidUpdateBlockedByRollback)988 TEST_F(OmahaRequestActionTest, ValidUpdateBlockedByRollback) {
989 string rollback_version = "1234.0.0";
990 MockPayloadState mock_payload_state;
991 fake_system_state_.set_payload_state(&mock_payload_state);
992 fake_update_response_.version = rollback_version;
993 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
994 tuc_params_.expected_code = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
995 tuc_params_.expected_check_reaction = metrics::CheckReaction::kIgnored;
996
997 EXPECT_CALL(mock_payload_state, GetRollbackVersion())
998 .WillRepeatedly(Return(rollback_version));
999
1000 ASSERT_FALSE(TestUpdateCheck());
1001
1002 EXPECT_FALSE(response.update_exists);
1003 }
1004
1005 // Verify that update checks called during OOBE will not try to download an
1006 // update if the response doesn't include the deadline field.
TEST_F(OmahaRequestActionTest,SkipNonCriticalUpdatesBeforeOOBE)1007 TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBE) {
1008 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1009 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1010 tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
1011 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1012 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1013
1014 // TODO(senj): set better default value for metrics::checkresult in
1015 // OmahaRequestAction::ActionCompleted.
1016 ASSERT_FALSE(TestUpdateCheck());
1017
1018 EXPECT_FALSE(response.update_exists);
1019 }
1020
1021 // Verify that the IsOOBEComplete() value is ignored when the OOBE flow is not
1022 // enabled.
TEST_F(OmahaRequestActionTest,SkipNonCriticalUpdatesBeforeOOBEDisabled)1023 TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBEDisabled) {
1024 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1025 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(false);
1026 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1027
1028 ASSERT_TRUE(TestUpdateCheck());
1029
1030 EXPECT_TRUE(response.update_exists);
1031 }
1032
1033 // Verify that update checks called during OOBE will still try to download an
1034 // update if the response includes the deadline field.
TEST_F(OmahaRequestActionTest,SkipNonCriticalUpdatesBeforeOOBEDeadlineSet)1035 TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBEDeadlineSet) {
1036 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1037 fake_update_response_.deadline = "20101020";
1038 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1039
1040 ASSERT_TRUE(TestUpdateCheck());
1041
1042 EXPECT_TRUE(response.update_exists);
1043 }
1044
1045 // Verify that update checks called during OOBE will not try to download an
1046 // update if a rollback happened, even when the response includes the deadline
1047 // field.
TEST_F(OmahaRequestActionTest,SkipNonCriticalUpdatesBeforeOOBERollback)1048 TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBERollback) {
1049 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1050 fake_update_response_.deadline = "20101020";
1051 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1052 tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
1053 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1054 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1055
1056 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetRollbackHappened())
1057 .WillOnce(Return(true));
1058
1059 ASSERT_FALSE(TestUpdateCheck());
1060
1061 EXPECT_FALSE(response.update_exists);
1062 }
1063
1064 // Verify that non-critical updates are skipped by reporting the
1065 // kNonCriticalUpdateInOOBE error code when attempted over cellular network -
1066 // i.e. when the update would need user permission. Note that reporting
1067 // kOmahaUpdateIgnoredOverCellular error in this case might cause undesired UX
1068 // in OOBE (warning the user about an update that will be skipped).
TEST_F(OmahaRequestActionTest,SkipNonCriticalUpdatesInOOBEOverCellular)1069 TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesInOOBEOverCellular) {
1070 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1071
1072 MockConnectionManager mock_cm;
1073 fake_system_state_.set_connection_manager(&mock_cm);
1074 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1075 tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
1076 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1077 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1078
1079 EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
1080 .WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
1081 SetArgPointee<1>(ConnectionTethering::kUnknown),
1082 Return(true)));
1083 EXPECT_CALL(mock_cm, IsAllowedConnectionTypesForUpdateSet())
1084 .WillRepeatedly(Return(false));
1085
1086 ASSERT_FALSE(TestUpdateCheck());
1087
1088 EXPECT_FALSE(response.update_exists);
1089 }
1090
TEST_F(OmahaRequestActionTest,WallClockBasedWaitAloneCausesScattering)1091 TEST_F(OmahaRequestActionTest, WallClockBasedWaitAloneCausesScattering) {
1092 request_params_.set_wall_clock_based_wait_enabled(true);
1093 request_params_.set_update_check_count_wait_enabled(false);
1094 request_params_.set_waiting_period(TimeDelta::FromDays(2));
1095 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1096 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1097 tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
1098 tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
1099
1100 ASSERT_FALSE(TestUpdateCheck());
1101
1102 EXPECT_FALSE(response.update_exists);
1103 }
1104
TEST_F(OmahaRequestActionTest,WallClockBasedWaitAloneCausesScatteringInteractive)1105 TEST_F(OmahaRequestActionTest,
1106 WallClockBasedWaitAloneCausesScatteringInteractive) {
1107 request_params_.set_wall_clock_based_wait_enabled(true);
1108 request_params_.set_update_check_count_wait_enabled(false);
1109 request_params_.set_waiting_period(TimeDelta::FromDays(2));
1110 request_params_.set_interactive(true);
1111 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1112 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1113
1114 // Verify if we are interactive check we don't defer.
1115 ASSERT_TRUE(TestUpdateCheck());
1116
1117 EXPECT_TRUE(response.update_exists);
1118 }
1119
TEST_F(OmahaRequestActionTest,NoWallClockBasedWaitCausesNoScattering)1120 TEST_F(OmahaRequestActionTest, NoWallClockBasedWaitCausesNoScattering) {
1121 request_params_.set_wall_clock_based_wait_enabled(false);
1122 request_params_.set_waiting_period(TimeDelta::FromDays(2));
1123 request_params_.set_update_check_count_wait_enabled(true);
1124 request_params_.set_min_update_checks_needed(1);
1125 request_params_.set_max_update_checks_allowed(8);
1126 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1127
1128 ASSERT_TRUE(TestUpdateCheck());
1129
1130 EXPECT_TRUE(response.update_exists);
1131 }
1132
TEST_F(OmahaRequestActionTest,ZeroMaxDaysToScatterCausesNoScattering)1133 TEST_F(OmahaRequestActionTest, ZeroMaxDaysToScatterCausesNoScattering) {
1134 request_params_.set_wall_clock_based_wait_enabled(true);
1135 request_params_.set_waiting_period(TimeDelta::FromDays(2));
1136 request_params_.set_update_check_count_wait_enabled(true);
1137 request_params_.set_min_update_checks_needed(1);
1138 request_params_.set_max_update_checks_allowed(8);
1139 fake_update_response_.max_days_to_scatter = "0";
1140 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1141
1142 ASSERT_TRUE(TestUpdateCheck());
1143
1144 EXPECT_TRUE(response.update_exists);
1145 }
1146
TEST_F(OmahaRequestActionTest,ZeroUpdateCheckCountCausesNoScattering)1147 TEST_F(OmahaRequestActionTest, ZeroUpdateCheckCountCausesNoScattering) {
1148 request_params_.set_wall_clock_based_wait_enabled(true);
1149 request_params_.set_waiting_period(TimeDelta());
1150 request_params_.set_update_check_count_wait_enabled(true);
1151 request_params_.set_min_update_checks_needed(0);
1152 request_params_.set_max_update_checks_allowed(0);
1153 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1154 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1155
1156 ASSERT_TRUE(TestUpdateCheck());
1157
1158 int64_t count;
1159 ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
1160 ASSERT_EQ(count, 0);
1161 EXPECT_TRUE(response.update_exists);
1162 }
1163
TEST_F(OmahaRequestActionTest,NonZeroUpdateCheckCountCausesScattering)1164 TEST_F(OmahaRequestActionTest, NonZeroUpdateCheckCountCausesScattering) {
1165 request_params_.set_wall_clock_based_wait_enabled(true);
1166 request_params_.set_waiting_period(TimeDelta());
1167 request_params_.set_update_check_count_wait_enabled(true);
1168 request_params_.set_min_update_checks_needed(1);
1169 request_params_.set_max_update_checks_allowed(8);
1170 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1171 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1172 tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
1173 tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
1174
1175 ASSERT_FALSE(TestUpdateCheck());
1176
1177 int64_t count;
1178 ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
1179 ASSERT_GT(count, 0);
1180 EXPECT_FALSE(response.update_exists);
1181 }
1182
TEST_F(OmahaRequestActionTest,NonZeroUpdateCheckCountCausesScatteringInteractive)1183 TEST_F(OmahaRequestActionTest,
1184 NonZeroUpdateCheckCountCausesScatteringInteractive) {
1185 request_params_.set_wall_clock_based_wait_enabled(true);
1186 request_params_.set_waiting_period(TimeDelta());
1187 request_params_.set_update_check_count_wait_enabled(true);
1188 request_params_.set_min_update_checks_needed(1);
1189 request_params_.set_max_update_checks_allowed(8);
1190 request_params_.set_interactive(true);
1191 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1192 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1193
1194 // Verify if we are interactive check we don't defer.
1195 ASSERT_TRUE(TestUpdateCheck());
1196
1197 EXPECT_TRUE(response.update_exists);
1198 }
1199
TEST_F(OmahaRequestActionTest,ExistingUpdateCheckCountCausesScattering)1200 TEST_F(OmahaRequestActionTest, ExistingUpdateCheckCountCausesScattering) {
1201 request_params_.set_wall_clock_based_wait_enabled(true);
1202 request_params_.set_waiting_period(TimeDelta());
1203 request_params_.set_update_check_count_wait_enabled(true);
1204 request_params_.set_min_update_checks_needed(1);
1205 request_params_.set_max_update_checks_allowed(8);
1206 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1207 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1208 tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
1209 tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
1210
1211 ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsUpdateCheckCount, 5));
1212 ASSERT_FALSE(TestUpdateCheck());
1213
1214 int64_t count;
1215 ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
1216 // |count| remains the same, as the decrementing happens in update_attempter
1217 // which this test doesn't exercise.
1218 ASSERT_EQ(count, 5);
1219 EXPECT_FALSE(response.update_exists);
1220 }
1221
TEST_F(OmahaRequestActionTest,ExistingUpdateCheckCountCausesScatteringInteractive)1222 TEST_F(OmahaRequestActionTest,
1223 ExistingUpdateCheckCountCausesScatteringInteractive) {
1224 request_params_.set_wall_clock_based_wait_enabled(true);
1225 request_params_.set_waiting_period(TimeDelta());
1226 request_params_.set_update_check_count_wait_enabled(true);
1227 request_params_.set_min_update_checks_needed(1);
1228 request_params_.set_max_update_checks_allowed(8);
1229 request_params_.set_interactive(true);
1230 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1231 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1232
1233 ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsUpdateCheckCount, 5));
1234
1235 // Verify if we are interactive check we don't defer.
1236 ASSERT_TRUE(TestUpdateCheck());
1237 EXPECT_TRUE(response.update_exists);
1238 }
1239
TEST_F(OmahaRequestActionTest,StagingTurnedOnCausesScattering)1240 TEST_F(OmahaRequestActionTest, StagingTurnedOnCausesScattering) {
1241 // If staging is on, the value for max days to scatter should be ignored, and
1242 // staging's scatter value should be used.
1243 request_params_.set_wall_clock_based_wait_enabled(true);
1244 request_params_.set_waiting_period(TimeDelta::FromDays(6));
1245 request_params_.set_update_check_count_wait_enabled(false);
1246 fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
1247
1248 ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsWallClockStagingWaitPeriod, 6));
1249 // This should not prevent scattering due to staging.
1250 fake_update_response_.max_days_to_scatter = "0";
1251 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1252 tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
1253 tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
1254
1255 ASSERT_FALSE(TestUpdateCheck());
1256
1257 EXPECT_FALSE(response.update_exists);
1258
1259 // Interactive updates should not be affected.
1260 request_params_.set_interactive(true);
1261 tuc_params_.expected_code = ErrorCode::kSuccess;
1262 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUpdating;
1263
1264 ASSERT_TRUE(TestUpdateCheck());
1265
1266 EXPECT_TRUE(response.update_exists);
1267 }
1268
TEST_F(OmahaRequestActionTest,CohortsArePersisted)1269 TEST_F(OmahaRequestActionTest, CohortsArePersisted) {
1270 fake_update_response_.include_cohorts = true;
1271 fake_update_response_.cohort = "s/154454/8479665";
1272 fake_update_response_.cohorthint = "please-put-me-on-beta";
1273 fake_update_response_.cohortname = "stable";
1274 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1275
1276 ASSERT_TRUE(TestUpdateCheck());
1277
1278 string value;
1279 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
1280 EXPECT_EQ(fake_update_response_.cohort, value);
1281
1282 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
1283 EXPECT_EQ(fake_update_response_.cohorthint, value);
1284
1285 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
1286 EXPECT_EQ(fake_update_response_.cohortname, value);
1287 }
1288
TEST_F(OmahaRequestActionTest,CohortsAreUpdated)1289 TEST_F(OmahaRequestActionTest, CohortsAreUpdated) {
1290 EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohort, "old_value"));
1291 EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohortHint, "old_hint"));
1292 EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohortName, "old_name"));
1293 fake_update_response_.include_cohorts = true;
1294 fake_update_response_.cohort = "s/154454/8479665";
1295 fake_update_response_.cohorthint = "please-put-me-on-beta";
1296 fake_update_response_.cohortname = "";
1297 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1298
1299 ASSERT_TRUE(TestUpdateCheck());
1300
1301 string value;
1302 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
1303 EXPECT_EQ(fake_update_response_.cohort, value);
1304
1305 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
1306 EXPECT_EQ(fake_update_response_.cohorthint, value);
1307
1308 EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
1309 }
1310
TEST_F(OmahaRequestActionTest,CohortsAreNotModifiedWhenMissing)1311 TEST_F(OmahaRequestActionTest, CohortsAreNotModifiedWhenMissing) {
1312 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1313
1314 EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohort, "old_value"));
1315 ASSERT_TRUE(TestUpdateCheck());
1316
1317 string value;
1318 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
1319 EXPECT_EQ("old_value", value);
1320
1321 EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
1322 EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
1323 }
1324
TEST_F(OmahaRequestActionTest,CohortsArePersistedWhenNoUpdate)1325 TEST_F(OmahaRequestActionTest, CohortsArePersistedWhenNoUpdate) {
1326 fake_update_response_.include_cohorts = true;
1327 fake_update_response_.cohort = "s/154454/8479665";
1328 fake_update_response_.cohorthint = "please-put-me-on-beta";
1329 fake_update_response_.cohortname = "stable";
1330 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1331 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1332 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1333
1334 ASSERT_TRUE(TestUpdateCheck());
1335
1336 string value;
1337 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
1338 EXPECT_EQ(fake_update_response_.cohort, value);
1339
1340 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
1341 EXPECT_EQ(fake_update_response_.cohorthint, value);
1342
1343 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
1344 EXPECT_EQ(fake_update_response_.cohortname, value);
1345 }
1346
TEST_F(OmahaRequestActionTest,MultiAppCohortTest)1347 TEST_F(OmahaRequestActionTest, MultiAppCohortTest) {
1348 fake_update_response_.multi_app = true;
1349 fake_update_response_.include_cohorts = true;
1350 fake_update_response_.cohort = "s/154454/8479665";
1351 fake_update_response_.cohorthint = "please-put-me-on-beta";
1352 fake_update_response_.cohortname = "stable";
1353 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1354
1355 ASSERT_TRUE(TestUpdateCheck());
1356
1357 string value;
1358 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
1359 EXPECT_EQ(fake_update_response_.cohort, value);
1360
1361 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
1362 EXPECT_EQ(fake_update_response_.cohorthint, value);
1363
1364 EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
1365 EXPECT_EQ(fake_update_response_.cohortname, value);
1366 }
1367
TEST_F(OmahaRequestActionTest,NoOutputPipeTest)1368 TEST_F(OmahaRequestActionTest, NoOutputPipeTest) {
1369 const string http_response(fake_update_response_.GetNoUpdateResponse());
1370 brillo::FakeMessageLoop loop(nullptr);
1371 loop.SetAsCurrent();
1372
1373 auto action = std::make_unique<OmahaRequestAction>(
1374 &fake_system_state_,
1375 nullptr,
1376 std::make_unique<MockHttpFetcher>(
1377 http_response.data(), http_response.size(), nullptr),
1378 false,
1379 "");
1380 ActionProcessor processor;
1381 processor.set_delegate(&delegate_);
1382 processor.EnqueueAction(std::move(action));
1383
1384 loop.PostTask(base::Bind(
1385 [](ActionProcessor* processor) { processor->StartProcessing(); },
1386 base::Unretained(&processor)));
1387 loop.Run();
1388 EXPECT_FALSE(loop.PendingTasks());
1389 EXPECT_FALSE(processor.IsRunning());
1390 }
1391
TEST_F(OmahaRequestActionTest,InvalidXmlTest)1392 TEST_F(OmahaRequestActionTest, InvalidXmlTest) {
1393 tuc_params_.http_response = "invalid xml>";
1394 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1395 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1396 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1397
1398 ASSERT_FALSE(TestUpdateCheck());
1399 EXPECT_FALSE(response.update_exists);
1400 }
1401
TEST_F(OmahaRequestActionTest,EmptyResponseTest)1402 TEST_F(OmahaRequestActionTest, EmptyResponseTest) {
1403 tuc_params_.expected_code = ErrorCode::kOmahaRequestEmptyResponseError;
1404 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1405 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1406
1407 ASSERT_FALSE(TestUpdateCheck());
1408 EXPECT_FALSE(response.update_exists);
1409 }
1410
TEST_F(OmahaRequestActionTest,MissingStatusTest)1411 TEST_F(OmahaRequestActionTest, MissingStatusTest) {
1412 tuc_params_.http_response =
1413 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
1414 "<daystart elapsed_seconds=\"100\"/>"
1415 "<app appid=\"foo\" status=\"ok\">"
1416 "<ping status=\"ok\"/>"
1417 "<updatecheck/></app></response>";
1418 tuc_params_.expected_code = ErrorCode::kOmahaResponseInvalid;
1419 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1420 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1421
1422 ASSERT_FALSE(TestUpdateCheck());
1423 EXPECT_FALSE(response.update_exists);
1424 }
1425
TEST_F(OmahaRequestActionTest,InvalidStatusTest)1426 TEST_F(OmahaRequestActionTest, InvalidStatusTest) {
1427 tuc_params_.http_response =
1428 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
1429 "<daystart elapsed_seconds=\"100\"/>"
1430 "<app appid=\"foo\" status=\"ok\">"
1431 "<ping status=\"ok\"/>"
1432 "<updatecheck status=\"InvalidStatusTest\"/></app></response>";
1433 tuc_params_.expected_code = ErrorCode::kOmahaResponseInvalid;
1434 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1435 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1436
1437 ASSERT_FALSE(TestUpdateCheck());
1438 EXPECT_FALSE(response.update_exists);
1439 }
1440
TEST_F(OmahaRequestActionTest,MissingNodesetTest)1441 TEST_F(OmahaRequestActionTest, MissingNodesetTest) {
1442 tuc_params_.http_response =
1443 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
1444 "<daystart elapsed_seconds=\"100\"/>"
1445 "<app appid=\"foo\" status=\"ok\">"
1446 "<ping status=\"ok\"/>"
1447 "</app></response>";
1448 tuc_params_.expected_code = ErrorCode::kOmahaResponseInvalid;
1449 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1450 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1451
1452 ASSERT_FALSE(TestUpdateCheck());
1453 EXPECT_FALSE(response.update_exists);
1454 }
1455
TEST_F(OmahaRequestActionTest,MissingFieldTest)1456 TEST_F(OmahaRequestActionTest, MissingFieldTest) {
1457 tuc_params_.http_response =
1458 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
1459 "<daystart elapsed_seconds=\"100\"/>"
1460 // the appid needs to match that in the request params
1461 "<app appid=\"" +
1462 fake_update_response_.app_id +
1463 "\" status=\"ok\">"
1464 "<updatecheck status=\"ok\">"
1465 "<urls><url codebase=\"http://missing/field/test/\"/></urls>"
1466 "<manifest version=\"10.2.3.4\">"
1467 "<packages><package hash=\"not-used\" name=\"f\" "
1468 "size=\"587\" hash_sha256=\"lkq34j5345\"/></packages>"
1469 "<actions><action event=\"postinstall\" "
1470 "Prompt=\"false\" "
1471 "IsDeltaPayload=\"false\" "
1472 "sha256=\"not-used\" "
1473 "/></actions></manifest></updatecheck></app></response>";
1474
1475 ASSERT_TRUE(TestUpdateCheck());
1476
1477 EXPECT_TRUE(response.update_exists);
1478 EXPECT_EQ("10.2.3.4", response.version);
1479 EXPECT_EQ("http://missing/field/test/f",
1480 response.packages[0].payload_urls[0]);
1481 EXPECT_EQ("", response.more_info_url);
1482 EXPECT_EQ("lkq34j5345", response.packages[0].hash);
1483 EXPECT_EQ(587u, response.packages[0].size);
1484 EXPECT_FALSE(response.prompt);
1485 EXPECT_TRUE(response.deadline.empty());
1486 }
1487
1488 namespace {
1489 class TerminateEarlyTestProcessorDelegate : public ActionProcessorDelegate {
1490 public:
ProcessingStopped(const ActionProcessor * processor)1491 void ProcessingStopped(const ActionProcessor* processor) {
1492 brillo::MessageLoop::current()->BreakLoop();
1493 }
1494 };
1495
TerminateTransferTestStarter(ActionProcessor * processor)1496 void TerminateTransferTestStarter(ActionProcessor* processor) {
1497 processor->StartProcessing();
1498 CHECK(processor->IsRunning());
1499 processor->StopProcessing();
1500 }
1501 } // namespace
1502
TEST_F(OmahaRequestActionTest,TerminateTransferTest)1503 TEST_F(OmahaRequestActionTest, TerminateTransferTest) {
1504 brillo::FakeMessageLoop loop(nullptr);
1505 loop.SetAsCurrent();
1506
1507 string http_response("doesn't matter");
1508 auto action = std::make_unique<OmahaRequestAction>(
1509 &fake_system_state_,
1510 nullptr,
1511 std::make_unique<MockHttpFetcher>(
1512 http_response.data(), http_response.size(), nullptr),
1513 false,
1514 "");
1515 TerminateEarlyTestProcessorDelegate delegate;
1516 ActionProcessor processor;
1517 processor.set_delegate(&delegate);
1518 processor.EnqueueAction(std::move(action));
1519
1520 loop.PostTask(base::Bind(&TerminateTransferTestStarter, &processor));
1521 loop.Run();
1522 EXPECT_FALSE(loop.PendingTasks());
1523 }
1524
TEST_F(OmahaRequestActionTest,XmlEncodeIsUsedForParams)1525 TEST_F(OmahaRequestActionTest, XmlEncodeIsUsedForParams) {
1526 // Make sure XML Encode is being called on the params.
1527 request_params_.set_os_sp("testtheservice_pack>");
1528 request_params_.set_os_board("x86 generic<id");
1529 request_params_.set_current_channel("unittest_track<");
1530 request_params_.set_target_channel("unittest_track<");
1531 request_params_.set_hwid("<OEM MODEL>");
1532 fake_prefs_.SetString(kPrefsOmahaCohort, "evil\nstring");
1533 fake_prefs_.SetString(kPrefsOmahaCohortHint, "evil&string\\");
1534 fake_prefs_.SetString(
1535 kPrefsOmahaCohortName,
1536 base::JoinString(vector<string>(100, "My spoon is too big."), " "));
1537 tuc_params_.http_response = "invalid xml>";
1538 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1539 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1540 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1541
1542 ASSERT_FALSE(TestUpdateCheck());
1543
1544 EXPECT_NE(string::npos, post_str.find("testtheservice_pack>"));
1545 EXPECT_EQ(string::npos, post_str.find("testtheservice_pack>"));
1546 EXPECT_NE(string::npos, post_str.find("x86 generic<id"));
1547 EXPECT_EQ(string::npos, post_str.find("x86 generic<id"));
1548 EXPECT_NE(string::npos, post_str.find("unittest_track&lt;"));
1549 EXPECT_EQ(string::npos, post_str.find("unittest_track<"));
1550 EXPECT_NE(string::npos, post_str.find("<OEM MODEL>"));
1551 EXPECT_EQ(string::npos, post_str.find("<OEM MODEL>"));
1552 EXPECT_NE(string::npos, post_str.find("cohort=\"evil\nstring\""));
1553 EXPECT_EQ(string::npos, post_str.find("cohorthint=\"evil&string\\\""));
1554 EXPECT_NE(string::npos, post_str.find("cohorthint=\"evil&string\\\""));
1555 // Values from Prefs that are too big are removed from the XML instead of
1556 // encoded.
1557 EXPECT_EQ(string::npos, post_str.find("cohortname="));
1558 }
1559
TEST_F(OmahaRequestActionTest,XmlDecodeTest)1560 TEST_F(OmahaRequestActionTest, XmlDecodeTest) {
1561 fake_update_response_.deadline = "<20110101";
1562 fake_update_response_.more_info_url = "testthe<url";
1563 fake_update_response_.codebase = "testthe&codebase/";
1564 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1565
1566 ASSERT_TRUE(TestUpdateCheck());
1567
1568 EXPECT_EQ("testthe<url", response.more_info_url);
1569 EXPECT_EQ("testthe&codebase/file.signed",
1570 response.packages[0].payload_urls[0]);
1571 EXPECT_EQ("<20110101", response.deadline);
1572 }
1573
TEST_F(OmahaRequestActionTest,ParseIntTest)1574 TEST_F(OmahaRequestActionTest, ParseIntTest) {
1575 // overflows int32_t:
1576 fake_update_response_.size = 123123123123123ull;
1577 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
1578
1579 ASSERT_TRUE(TestUpdateCheck());
1580 EXPECT_EQ(fake_update_response_.size, response.packages[0].size);
1581 }
1582
TEST_F(OmahaRequestActionTest,FormatUpdateCheckOutputTest)1583 TEST_F(OmahaRequestActionTest, FormatUpdateCheckOutputTest) {
1584 NiceMock<MockPrefs> prefs;
1585 fake_system_state_.set_prefs(&prefs);
1586 tuc_params_.http_response = "invalid xml>";
1587 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1588 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1589 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1590
1591 EXPECT_CALL(prefs, GetString(kPrefsPreviousVersion, _))
1592 .WillOnce(DoAll(SetArgPointee<1>(string("")), Return(true)));
1593 // An existing but empty previous version means that we didn't reboot to a new
1594 // update, therefore, no need to update the previous version.
1595 EXPECT_CALL(prefs, SetString(kPrefsPreviousVersion, _)).Times(0);
1596 ASSERT_FALSE(TestUpdateCheck());
1597
1598 EXPECT_NE(
1599 post_str.find(" <ping active=\"1\" a=\"-1\" r=\"-1\"></ping>\n"
1600 " <updatecheck></updatecheck>\n"),
1601 string::npos);
1602 EXPECT_NE(post_str.find("hardware_class=\"OEM MODEL 09235 7471\""),
1603 string::npos);
1604 EXPECT_NE(post_str.find("fw_version=\"ChromeOSFirmware.1.0\""), string::npos);
1605 EXPECT_NE(post_str.find("ec_version=\"0X0A1\""), string::npos);
1606 // No <event> tag should be sent if we didn't reboot to an update.
1607 EXPECT_EQ(post_str.find("<event"), string::npos);
1608 }
1609
TEST_F(OmahaRequestActionTest,FormatSuccessEventOutputTest)1610 TEST_F(OmahaRequestActionTest, FormatSuccessEventOutputTest) {
1611 TestEvent(new OmahaEvent(OmahaEvent::kTypeUpdateDownloadStarted),
1612 "invalid xml>");
1613
1614 string expected_event = base::StringPrintf(
1615 " <event eventtype=\"%d\" eventresult=\"%d\"></event>\n",
1616 OmahaEvent::kTypeUpdateDownloadStarted,
1617 OmahaEvent::kResultSuccess);
1618 EXPECT_NE(post_str.find(expected_event), string::npos);
1619 EXPECT_EQ(post_str.find("ping"), string::npos);
1620 EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1621 }
1622
TEST_F(OmahaRequestActionTest,FormatErrorEventOutputTest)1623 TEST_F(OmahaRequestActionTest, FormatErrorEventOutputTest) {
1624 TestEvent(new OmahaEvent(OmahaEvent::kTypeDownloadComplete,
1625 OmahaEvent::kResultError,
1626 ErrorCode::kError),
1627 "invalid xml>");
1628
1629 string expected_event = base::StringPrintf(
1630 " <event eventtype=\"%d\" eventresult=\"%d\" "
1631 "errorcode=\"%d\"></event>\n",
1632 OmahaEvent::kTypeDownloadComplete,
1633 OmahaEvent::kResultError,
1634 static_cast<int>(ErrorCode::kError));
1635 EXPECT_NE(post_str.find(expected_event), string::npos);
1636 EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1637 }
1638
TEST_F(OmahaRequestActionTest,IsEventTest)1639 TEST_F(OmahaRequestActionTest, IsEventTest) {
1640 string http_response("doesn't matter");
1641 OmahaRequestAction update_check_action(
1642 &fake_system_state_,
1643 nullptr,
1644 std::make_unique<MockHttpFetcher>(
1645 http_response.data(), http_response.size(), nullptr),
1646 false,
1647 "");
1648 EXPECT_FALSE(update_check_action.IsEvent());
1649
1650 OmahaRequestAction event_action(
1651 &fake_system_state_,
1652 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
1653 std::make_unique<MockHttpFetcher>(
1654 http_response.data(), http_response.size(), nullptr),
1655 false,
1656 "");
1657 EXPECT_TRUE(event_action.IsEvent());
1658 }
1659
TEST_F(OmahaRequestActionTest,FormatDeltaOkayOutputTest)1660 TEST_F(OmahaRequestActionTest, FormatDeltaOkayOutputTest) {
1661 tuc_params_.http_response = "invalid xml>";
1662 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1663 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1664 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1665
1666 for (int i = 0; i < 2; i++) {
1667 bool delta_okay = i == 1;
1668 const char* delta_okay_str = delta_okay ? "true" : "false";
1669 request_params_.set_delta_okay(delta_okay);
1670
1671 ASSERT_FALSE(TestUpdateCheck());
1672 EXPECT_NE(
1673 post_str.find(base::StringPrintf(" delta_okay=\"%s\"", delta_okay_str)),
1674 string::npos)
1675 << "i = " << i;
1676 }
1677 }
1678
TEST_F(OmahaRequestActionTest,FormatInteractiveOutputTest)1679 TEST_F(OmahaRequestActionTest, FormatInteractiveOutputTest) {
1680 tuc_params_.http_response = "invalid xml>";
1681 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1682 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1683 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1684
1685 for (int i = 0; i < 2; i++) {
1686 bool interactive = i == 1;
1687 const char* interactive_str = interactive ? "ondemandupdate" : "scheduler";
1688 request_params_.set_interactive(interactive);
1689
1690 ASSERT_FALSE(TestUpdateCheck());
1691 EXPECT_NE(post_str.find(
1692 base::StringPrintf("installsource=\"%s\"", interactive_str)),
1693 string::npos)
1694 << "i = " << i;
1695 }
1696 }
1697
TEST_F(OmahaRequestActionTest,FormatTargetVersionPrefixOutputTest)1698 TEST_F(OmahaRequestActionTest, FormatTargetVersionPrefixOutputTest) {
1699 tuc_params_.http_response = "invalid xml>";
1700 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1701 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1702 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1703
1704 for (int i = 0; i < 2; i++) {
1705 bool target_version_set = i == 1;
1706 const char* target_version_prefix = target_version_set ? "10032." : "";
1707 request_params_.set_target_version_prefix(target_version_prefix);
1708
1709 ASSERT_FALSE(TestUpdateCheck());
1710 if (target_version_set) {
1711 EXPECT_NE(post_str.find("<updatecheck targetversionprefix=\"10032.\">"),
1712 string::npos)
1713 << "i = " << i;
1714 } else {
1715 EXPECT_EQ(post_str.find("targetversionprefix"), string::npos)
1716 << "i = " << i;
1717 }
1718 }
1719 }
1720
TEST_F(OmahaRequestActionTest,FormatRollbackAllowedOutputTest)1721 TEST_F(OmahaRequestActionTest, FormatRollbackAllowedOutputTest) {
1722 tuc_params_.http_response = "invalid xml>";
1723 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
1724 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
1725 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1726
1727 for (int i = 0; i < 4; i++) {
1728 bool rollback_allowed = i / 2 == 0;
1729 bool target_version_set = i % 2 == 0;
1730 request_params_.set_target_version_prefix(target_version_set ? "10032."
1731 : "");
1732 request_params_.set_rollback_allowed(rollback_allowed);
1733
1734 ASSERT_FALSE(TestUpdateCheck());
1735 if (rollback_allowed && target_version_set) {
1736 EXPECT_NE(post_str.find("rollback_allowed=\"true\""), string::npos)
1737 << "i = " << i;
1738 } else {
1739 EXPECT_EQ(post_str.find("rollback_allowed"), string::npos) << "i = " << i;
1740 }
1741 }
1742 }
1743
TEST_F(OmahaRequestActionTest,OmahaEventTest)1744 TEST_F(OmahaRequestActionTest, OmahaEventTest) {
1745 OmahaEvent default_event;
1746 EXPECT_EQ(OmahaEvent::kTypeUnknown, default_event.type);
1747 EXPECT_EQ(OmahaEvent::kResultError, default_event.result);
1748 EXPECT_EQ(ErrorCode::kError, default_event.error_code);
1749
1750 OmahaEvent success_event(OmahaEvent::kTypeUpdateDownloadStarted);
1751 EXPECT_EQ(OmahaEvent::kTypeUpdateDownloadStarted, success_event.type);
1752 EXPECT_EQ(OmahaEvent::kResultSuccess, success_event.result);
1753 EXPECT_EQ(ErrorCode::kSuccess, success_event.error_code);
1754
1755 OmahaEvent error_event(OmahaEvent::kTypeUpdateDownloadFinished,
1756 OmahaEvent::kResultError,
1757 ErrorCode::kError);
1758 EXPECT_EQ(OmahaEvent::kTypeUpdateDownloadFinished, error_event.type);
1759 EXPECT_EQ(OmahaEvent::kResultError, error_event.result);
1760 EXPECT_EQ(ErrorCode::kError, error_event.error_code);
1761 }
1762
TEST_F(OmahaRequestActionTest,DeviceQuickFixBuildTokenIsSetTest)1763 TEST_F(OmahaRequestActionTest, DeviceQuickFixBuildTokenIsSetTest) {
1764 // If DeviceQuickFixBuildToken value is set it takes precedence over pref
1765 // value.
1766 constexpr char autoupdate_token[] = "autoupdate_token>";
1767 constexpr char xml_encoded_autoupdate_token[] = "autoupdate_token>";
1768 constexpr char omaha_cohort_hint[] = "cohort_hint";
1769
1770 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1771 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1772 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1773 request_params_.set_autoupdate_token(autoupdate_token);
1774 fake_prefs_.SetString(kPrefsOmahaCohortHint, omaha_cohort_hint);
1775
1776 ASSERT_TRUE(TestUpdateCheck());
1777
1778 EXPECT_NE(string::npos,
1779 post_str.find("cohorthint=\"" +
1780 string(xml_encoded_autoupdate_token) + "\""));
1781 EXPECT_EQ(string::npos, post_str.find(autoupdate_token));
1782 EXPECT_EQ(string::npos, post_str.find(omaha_cohort_hint));
1783 }
1784
TEST_F(OmahaRequestActionTest,DeviceQuickFixBuildTokenIsNotSetTest)1785 TEST_F(OmahaRequestActionTest, DeviceQuickFixBuildTokenIsNotSetTest) {
1786 // If DeviceQuickFixBuildToken is not set, pref value will be provided in
1787 // cohorthint attribute.
1788 constexpr char omaha_cohort_hint[] = "evil_string>";
1789 constexpr char xml_encoded_cohort_hint[] = "evil_string>";
1790
1791 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1792 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1793 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1794 fake_prefs_.SetString(kPrefsOmahaCohortHint, omaha_cohort_hint);
1795
1796 ASSERT_TRUE(TestUpdateCheck());
1797
1798 EXPECT_NE(
1799 string::npos,
1800 post_str.find("cohorthint=\"" + string(xml_encoded_cohort_hint) + "\""));
1801 EXPECT_EQ(string::npos, post_str.find(omaha_cohort_hint));
1802 }
1803
PingTest(bool ping_only)1804 void OmahaRequestActionTest::PingTest(bool ping_only) {
1805 NiceMock<MockPrefs> prefs;
1806 fake_system_state_.set_prefs(&prefs);
1807 EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1808 .Times(AnyNumber());
1809 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1810 // Add a few hours to the day difference to test no rounding, etc.
1811 int64_t five_days_ago =
1812 (Time::Now() - TimeDelta::FromHours(5 * 24 + 13)).ToInternalValue();
1813 int64_t six_days_ago =
1814 (Time::Now() - TimeDelta::FromHours(6 * 24 + 11)).ToInternalValue();
1815 EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1816 .WillOnce(DoAll(SetArgPointee<1>(0), Return(true)));
1817 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1818 .WillOnce(DoAll(SetArgPointee<1>(six_days_ago), Return(true)));
1819 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1820 .WillOnce(DoAll(SetArgPointee<1>(five_days_ago), Return(true)));
1821
1822 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1823 tuc_params_.ping_only = ping_only;
1824 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1825 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1826
1827 ASSERT_TRUE(TestUpdateCheck());
1828
1829 EXPECT_NE(post_str.find("<ping active=\"1\" a=\"6\" r=\"5\"></ping>"),
1830 string::npos);
1831 if (ping_only) {
1832 EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1833 EXPECT_EQ(post_str.find("previousversion"), string::npos);
1834 } else {
1835 EXPECT_NE(post_str.find("updatecheck"), string::npos);
1836 EXPECT_NE(post_str.find("previousversion"), string::npos);
1837 }
1838 }
1839
TEST_F(OmahaRequestActionTest,PingTestSendOnlyAPing)1840 TEST_F(OmahaRequestActionTest, PingTestSendOnlyAPing) {
1841 PingTest(true /* ping_only */);
1842 }
1843
TEST_F(OmahaRequestActionTest,PingTestSendAlsoAnUpdateCheck)1844 TEST_F(OmahaRequestActionTest, PingTestSendAlsoAnUpdateCheck) {
1845 PingTest(false /* ping_only */);
1846 }
1847
TEST_F(OmahaRequestActionTest,ActivePingTest)1848 TEST_F(OmahaRequestActionTest, ActivePingTest) {
1849 NiceMock<MockPrefs> prefs;
1850 fake_system_state_.set_prefs(&prefs);
1851 EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1852 .Times(AnyNumber());
1853 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1854 int64_t three_days_ago =
1855 (Time::Now() - TimeDelta::FromHours(3 * 24 + 12)).ToInternalValue();
1856 int64_t now = Time::Now().ToInternalValue();
1857 EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1858 .WillOnce(DoAll(SetArgPointee<1>(0), Return(true)));
1859 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1860 .WillOnce(DoAll(SetArgPointee<1>(three_days_ago), Return(true)));
1861 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1862 .WillOnce(DoAll(SetArgPointee<1>(now), Return(true)));
1863
1864 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1865 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1866 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1867
1868 ASSERT_TRUE(TestUpdateCheck());
1869
1870 EXPECT_NE(post_str.find("<ping active=\"1\" a=\"3\"></ping>"), string::npos);
1871 }
1872
TEST_F(OmahaRequestActionTest,RollCallPingTest)1873 TEST_F(OmahaRequestActionTest, RollCallPingTest) {
1874 NiceMock<MockPrefs> prefs;
1875 fake_system_state_.set_prefs(&prefs);
1876 EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1877 .Times(AnyNumber());
1878 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1879 int64_t four_days_ago =
1880 (Time::Now() - TimeDelta::FromHours(4 * 24)).ToInternalValue();
1881 int64_t now = Time::Now().ToInternalValue();
1882 EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1883 .WillOnce(DoAll(SetArgPointee<1>(0), Return(true)));
1884 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1885 .WillOnce(DoAll(SetArgPointee<1>(now), Return(true)));
1886 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1887 .WillOnce(DoAll(SetArgPointee<1>(four_days_ago), Return(true)));
1888
1889 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1890 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1891 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1892
1893 ASSERT_TRUE(TestUpdateCheck());
1894
1895 EXPECT_NE(post_str.find("<ping active=\"1\" r=\"4\"></ping>\n"),
1896 string::npos);
1897 }
1898
TEST_F(OmahaRequestActionTest,NoPingTest)1899 TEST_F(OmahaRequestActionTest, NoPingTest) {
1900 NiceMock<MockPrefs> prefs;
1901 fake_system_state_.set_prefs(&prefs);
1902 EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1903 .Times(AnyNumber());
1904 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1905 int64_t one_hour_ago =
1906 (Time::Now() - TimeDelta::FromHours(1)).ToInternalValue();
1907 EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1908 .WillOnce(DoAll(SetArgPointee<1>(0), Return(true)));
1909 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1910 .WillOnce(DoAll(SetArgPointee<1>(one_hour_ago), Return(true)));
1911 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1912 .WillOnce(DoAll(SetArgPointee<1>(one_hour_ago), Return(true)));
1913 // LastActivePingDay and PrefsLastRollCallPingDay are set even if we didn't
1914 // send a ping.
1915 EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _))
1916 .WillOnce(Return(true));
1917 EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _))
1918 .WillOnce(Return(true));
1919
1920 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1921 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1922 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1923
1924 ASSERT_TRUE(TestUpdateCheck());
1925
1926 EXPECT_EQ(post_str.find("ping"), string::npos);
1927 }
1928
TEST_F(OmahaRequestActionTest,IgnoreEmptyPingTest)1929 TEST_F(OmahaRequestActionTest, IgnoreEmptyPingTest) {
1930 // This test ensures that we ignore empty ping only requests.
1931 NiceMock<MockPrefs> prefs;
1932 fake_system_state_.set_prefs(&prefs);
1933 int64_t now = Time::Now().ToInternalValue();
1934 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1935 .WillOnce(DoAll(SetArgPointee<1>(now), Return(true)));
1936 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1937 .WillOnce(DoAll(SetArgPointee<1>(now), Return(true)));
1938 EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
1939 EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
1940
1941 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
1942 tuc_params_.ping_only = true;
1943 tuc_params_.expected_check_result = metrics::CheckResult::kUnset;
1944 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1945
1946 EXPECT_TRUE(TestUpdateCheck());
1947 EXPECT_TRUE(post_str.empty());
1948 }
1949
TEST_F(OmahaRequestActionTest,BackInTimePingTest)1950 TEST_F(OmahaRequestActionTest, BackInTimePingTest) {
1951 NiceMock<MockPrefs> prefs;
1952 fake_system_state_.set_prefs(&prefs);
1953 EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1954 .Times(AnyNumber());
1955 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1956 int64_t future =
1957 (Time::Now() + TimeDelta::FromHours(3 * 24 + 4)).ToInternalValue();
1958 EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1959 .WillOnce(DoAll(SetArgPointee<1>(0), Return(true)));
1960 EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1961 .WillOnce(DoAll(SetArgPointee<1>(future), Return(true)));
1962 EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1963 .WillOnce(DoAll(SetArgPointee<1>(future), Return(true)));
1964 EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _))
1965 .WillOnce(Return(true));
1966 EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _))
1967 .WillOnce(Return(true));
1968
1969 tuc_params_.http_response =
1970 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
1971 "protocol=\"3.0\"><daystart elapsed_seconds=\"100\"/>"
1972 "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
1973 "<updatecheck status=\"noupdate\"/></app></response>";
1974 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
1975 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
1976
1977 ASSERT_TRUE(TestUpdateCheck());
1978 EXPECT_EQ(post_str.find("ping"), string::npos);
1979 }
1980
TEST_F(OmahaRequestActionTest,LastPingDayUpdateTest)1981 TEST_F(OmahaRequestActionTest, LastPingDayUpdateTest) {
1982 // This test checks that the action updates the last ping day to now
1983 // minus 200 seconds with a slack of 5 seconds. Therefore, the test
1984 // may fail if it runs for longer than 5 seconds. It shouldn't run
1985 // that long though.
1986 int64_t midnight =
1987 (Time::Now() - TimeDelta::FromSeconds(200)).ToInternalValue();
1988 int64_t midnight_slack =
1989 (Time::Now() - TimeDelta::FromSeconds(195)).ToInternalValue();
1990 NiceMock<MockPrefs> prefs;
1991 fake_system_state_.set_prefs(&prefs);
1992 EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
1993 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1994 EXPECT_CALL(prefs,
1995 SetInt64(kPrefsLastActivePingDay,
1996 AllOf(Ge(midnight), Le(midnight_slack))))
1997 .WillOnce(Return(true));
1998 EXPECT_CALL(prefs,
1999 SetInt64(kPrefsLastRollCallPingDay,
2000 AllOf(Ge(midnight), Le(midnight_slack))))
2001 .WillOnce(Return(true));
2002
2003 tuc_params_.http_response =
2004 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2005 "protocol=\"3.0\"><daystart elapsed_seconds=\"200\"/>"
2006 "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
2007 "<updatecheck status=\"noupdate\"/></app></response>";
2008 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2009 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2010
2011 ASSERT_TRUE(TestUpdateCheck());
2012 }
2013
TEST_F(OmahaRequestActionTest,NoElapsedSecondsTest)2014 TEST_F(OmahaRequestActionTest, NoElapsedSecondsTest) {
2015 NiceMock<MockPrefs> prefs;
2016 fake_system_state_.set_prefs(&prefs);
2017 EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
2018 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
2019 EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
2020 EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
2021
2022 tuc_params_.http_response =
2023 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2024 "protocol=\"3.0\"><daystart blah=\"200\"/>"
2025 "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
2026 "<updatecheck status=\"noupdate\"/></app></response>";
2027 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2028 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2029
2030 ASSERT_TRUE(TestUpdateCheck());
2031 }
2032
TEST_F(OmahaRequestActionTest,BadElapsedSecondsTest)2033 TEST_F(OmahaRequestActionTest, BadElapsedSecondsTest) {
2034 NiceMock<MockPrefs> prefs;
2035 fake_system_state_.set_prefs(&prefs);
2036 EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
2037 EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
2038 EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
2039 EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
2040
2041 tuc_params_.http_response =
2042 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2043 "protocol=\"3.0\"><daystart elapsed_seconds=\"x\"/>"
2044 "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
2045 "<updatecheck status=\"noupdate\"/></app></response>";
2046 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2047 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2048
2049 ASSERT_TRUE(TestUpdateCheck());
2050 }
2051
TEST_F(OmahaRequestActionTest,NoUniqueIDTest)2052 TEST_F(OmahaRequestActionTest, NoUniqueIDTest) {
2053 tuc_params_.http_response = "invalid xml>";
2054 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
2055 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
2056 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2057
2058 ASSERT_FALSE(TestUpdateCheck());
2059
2060 EXPECT_EQ(post_str.find("machineid="), string::npos);
2061 EXPECT_EQ(post_str.find("userid="), string::npos);
2062 }
2063
TEST_F(OmahaRequestActionTest,NetworkFailureTest)2064 TEST_F(OmahaRequestActionTest, NetworkFailureTest) {
2065 const int http_error_code =
2066 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + 501;
2067 tuc_params_.fail_http_response_code = 501;
2068 tuc_params_.expected_code = static_cast<ErrorCode>(http_error_code);
2069 tuc_params_.expected_check_result = metrics::CheckResult::kDownloadError;
2070 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2071 tuc_params_.expected_download_error_code =
2072 static_cast<metrics::DownloadErrorCode>(501);
2073
2074 ASSERT_FALSE(TestUpdateCheck());
2075
2076 EXPECT_FALSE(response.update_exists);
2077 }
2078
TEST_F(OmahaRequestActionTest,NetworkFailureBadHTTPCodeTest)2079 TEST_F(OmahaRequestActionTest, NetworkFailureBadHTTPCodeTest) {
2080 const int http_error_code =
2081 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + 999;
2082
2083 tuc_params_.fail_http_response_code = 1500;
2084 tuc_params_.expected_code = static_cast<ErrorCode>(http_error_code);
2085 tuc_params_.expected_check_result = metrics::CheckResult::kDownloadError;
2086 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2087 tuc_params_.expected_download_error_code =
2088 metrics::DownloadErrorCode::kHttpStatusOther;
2089
2090 ASSERT_FALSE(TestUpdateCheck());
2091 EXPECT_FALSE(response.update_exists);
2092 }
2093
TEST_F(OmahaRequestActionTest,TestUpdateFirstSeenAtGetsPersistedFirstTime)2094 TEST_F(OmahaRequestActionTest, TestUpdateFirstSeenAtGetsPersistedFirstTime) {
2095 request_params_.set_wall_clock_based_wait_enabled(true);
2096 request_params_.set_waiting_period(TimeDelta().FromDays(1));
2097 request_params_.set_update_check_count_wait_enabled(false);
2098
2099 Time arbitrary_date;
2100 ASSERT_TRUE(Time::FromString("6/4/1989", &arbitrary_date));
2101 fake_system_state_.fake_clock()->SetWallclockTime(arbitrary_date);
2102
2103 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2104 tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
2105 tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
2106
2107 ASSERT_FALSE(TestUpdateCheck());
2108
2109 int64_t timestamp = 0;
2110 ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateFirstSeenAt, ×tamp));
2111 EXPECT_EQ(arbitrary_date.ToInternalValue(), timestamp);
2112 EXPECT_FALSE(response.update_exists);
2113
2114 // Verify if we are interactive check we don't defer.
2115 request_params_.set_interactive(true);
2116 tuc_params_.expected_code = ErrorCode::kSuccess;
2117 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUpdating;
2118
2119 ASSERT_TRUE(TestUpdateCheck());
2120 EXPECT_TRUE(response.update_exists);
2121 }
2122
TEST_F(OmahaRequestActionTest,TestUpdateFirstSeenAtGetsUsedIfAlreadyPresent)2123 TEST_F(OmahaRequestActionTest, TestUpdateFirstSeenAtGetsUsedIfAlreadyPresent) {
2124 request_params_.set_wall_clock_based_wait_enabled(true);
2125 request_params_.set_waiting_period(TimeDelta().FromDays(1));
2126 request_params_.set_update_check_count_wait_enabled(false);
2127
2128 Time t1, t2;
2129 ASSERT_TRUE(Time::FromString("1/1/2012", &t1));
2130 ASSERT_TRUE(Time::FromString("1/3/2012", &t2));
2131 ASSERT_TRUE(
2132 fake_prefs_.SetInt64(kPrefsUpdateFirstSeenAt, t1.ToInternalValue()));
2133 fake_system_state_.fake_clock()->SetWallclockTime(t2);
2134
2135 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2136
2137 ASSERT_TRUE(TestUpdateCheck());
2138 EXPECT_TRUE(response.update_exists);
2139
2140 // Make sure the timestamp t1 is unchanged showing that it was reused.
2141 int64_t timestamp = 0;
2142 ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateFirstSeenAt, ×tamp));
2143 ASSERT_TRUE(timestamp == t1.ToInternalValue());
2144 }
2145
TEST_F(OmahaRequestActionTest,TestChangingToMoreStableChannel)2146 TEST_F(OmahaRequestActionTest, TestChangingToMoreStableChannel) {
2147 // Create a uniquely named test directory.
2148 base::ScopedTempDir tempdir;
2149 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
2150
2151 request_params_.set_root(tempdir.GetPath().value());
2152 request_params_.set_app_id("{22222222-2222-2222-2222-222222222222}");
2153 request_params_.set_app_version("1.2.3.4");
2154 request_params_.set_product_components("o.bundle=1");
2155 request_params_.set_current_channel("canary-channel");
2156 EXPECT_TRUE(
2157 request_params_.SetTargetChannel("stable-channel", true, nullptr));
2158 request_params_.UpdateDownloadChannel();
2159 EXPECT_TRUE(request_params_.ShouldPowerwash());
2160
2161 tuc_params_.http_response = "invalid xml>";
2162 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
2163 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
2164 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2165
2166 ASSERT_FALSE(TestUpdateCheck());
2167
2168 EXPECT_NE(
2169 string::npos,
2170 post_str.find("appid=\"{22222222-2222-2222-2222-222222222222}\" "
2171 "version=\"0.0.0.0\" from_version=\"1.2.3.4\" "
2172 "track=\"stable-channel\" from_track=\"canary-channel\" "));
2173 EXPECT_EQ(string::npos, post_str.find("o.bundle"));
2174 }
2175
TEST_F(OmahaRequestActionTest,TestChangingToLessStableChannel)2176 TEST_F(OmahaRequestActionTest, TestChangingToLessStableChannel) {
2177 // Create a uniquely named test directory.
2178 base::ScopedTempDir tempdir;
2179 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
2180
2181 request_params_.set_root(tempdir.GetPath().value());
2182 request_params_.set_app_id("{11111111-1111-1111-1111-111111111111}");
2183 request_params_.set_app_version("5.6.7.8");
2184 request_params_.set_product_components("o.bundle=1");
2185 request_params_.set_current_channel("stable-channel");
2186 EXPECT_TRUE(
2187 request_params_.SetTargetChannel("canary-channel", false, nullptr));
2188 request_params_.UpdateDownloadChannel();
2189 EXPECT_FALSE(request_params_.ShouldPowerwash());
2190
2191 tuc_params_.http_response = "invalid xml>";
2192 tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
2193 tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
2194 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2195
2196 ASSERT_FALSE(TestUpdateCheck());
2197
2198 EXPECT_NE(
2199 string::npos,
2200 post_str.find("appid=\"{11111111-1111-1111-1111-111111111111}\" "
2201 "version=\"5.6.7.8\" "
2202 "track=\"canary-channel\" from_track=\"stable-channel\""));
2203 EXPECT_EQ(string::npos, post_str.find("from_version"));
2204 EXPECT_NE(string::npos, post_str.find("o.bundle.version=\"1\""));
2205 }
2206
2207 // Checks that the initial ping with a=-1 r=-1 is not send when the device
2208 // was powerwashed.
TEST_F(OmahaRequestActionTest,PingWhenPowerwashed)2209 TEST_F(OmahaRequestActionTest, PingWhenPowerwashed) {
2210 fake_prefs_.SetString(kPrefsPreviousVersion, "");
2211
2212 // Flag that the device was powerwashed in the past.
2213 fake_system_state_.fake_hardware()->SetPowerwashCount(1);
2214 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
2215 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2216 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2217
2218 ASSERT_TRUE(TestUpdateCheck());
2219
2220 // We shouldn't send a ping in this case since powerwash > 0.
2221 EXPECT_EQ(string::npos, post_str.find("<ping"));
2222 }
2223
2224 // Checks that the initial ping with a=-1 r=-1 is not send when the device
2225 // first_active_omaha_ping_sent is set.
TEST_F(OmahaRequestActionTest,PingWhenFirstActiveOmahaPingIsSent)2226 TEST_F(OmahaRequestActionTest, PingWhenFirstActiveOmahaPingIsSent) {
2227 fake_prefs_.SetString(kPrefsPreviousVersion, "");
2228
2229 // Flag that the device was not powerwashed in the past.
2230 fake_system_state_.fake_hardware()->SetPowerwashCount(0);
2231
2232 // Flag that the device has sent first active ping in the past.
2233 fake_system_state_.fake_hardware()->SetFirstActiveOmahaPingSent();
2234
2235 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
2236 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2237 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2238
2239 ASSERT_TRUE(TestUpdateCheck());
2240
2241 // We shouldn't send a ping in this case since
2242 // first_active_omaha_ping_sent=true
2243 EXPECT_EQ(string::npos, post_str.find("<ping"));
2244 }
2245
2246 // Checks that the event 54 is sent on a reboot to a new update.
TEST_F(OmahaRequestActionTest,RebootAfterUpdateEvent)2247 TEST_F(OmahaRequestActionTest, RebootAfterUpdateEvent) {
2248 // Flag that the device was updated in a previous boot.
2249 fake_prefs_.SetString(kPrefsPreviousVersion, "1.2.3.4");
2250
2251 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
2252 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2253 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2254
2255 ASSERT_TRUE(TestUpdateCheck());
2256
2257 // An event 54 is included and has the right version.
2258 EXPECT_NE(
2259 string::npos,
2260 post_str.find(base::StringPrintf("<event eventtype=\"%d\"",
2261 OmahaEvent::kTypeRebootedAfterUpdate)));
2262 EXPECT_NE(string::npos,
2263 post_str.find("previousversion=\"1.2.3.4\"></event>"));
2264
2265 // The previous version flag should have been removed.
2266 EXPECT_TRUE(fake_prefs_.Exists(kPrefsPreviousVersion));
2267 string prev_version;
2268 EXPECT_TRUE(fake_prefs_.GetString(kPrefsPreviousVersion, &prev_version));
2269 EXPECT_TRUE(prev_version.empty());
2270 }
2271
P2PTest(bool initial_allow_p2p_for_downloading,bool initial_allow_p2p_for_sharing,bool omaha_disable_p2p_for_downloading,bool omaha_disable_p2p_for_sharing,bool payload_state_allow_p2p_attempt,bool expect_p2p_client_lookup,const string & p2p_client_result_url,bool expected_allow_p2p_for_downloading,bool expected_allow_p2p_for_sharing,const string & expected_p2p_url)2272 void OmahaRequestActionTest::P2PTest(bool initial_allow_p2p_for_downloading,
2273 bool initial_allow_p2p_for_sharing,
2274 bool omaha_disable_p2p_for_downloading,
2275 bool omaha_disable_p2p_for_sharing,
2276 bool payload_state_allow_p2p_attempt,
2277 bool expect_p2p_client_lookup,
2278 const string& p2p_client_result_url,
2279 bool expected_allow_p2p_for_downloading,
2280 bool expected_allow_p2p_for_sharing,
2281 const string& expected_p2p_url) {
2282 bool actual_allow_p2p_for_downloading = initial_allow_p2p_for_downloading;
2283 bool actual_allow_p2p_for_sharing = initial_allow_p2p_for_sharing;
2284 string actual_p2p_url;
2285
2286 MockPayloadState mock_payload_state;
2287 fake_system_state_.set_payload_state(&mock_payload_state);
2288 EXPECT_CALL(mock_payload_state, P2PAttemptAllowed())
2289 .WillRepeatedly(Return(payload_state_allow_p2p_attempt));
2290 EXPECT_CALL(mock_payload_state, GetUsingP2PForDownloading())
2291 .WillRepeatedly(ReturnPointee(&actual_allow_p2p_for_downloading));
2292 EXPECT_CALL(mock_payload_state, GetUsingP2PForSharing())
2293 .WillRepeatedly(ReturnPointee(&actual_allow_p2p_for_sharing));
2294 EXPECT_CALL(mock_payload_state, SetUsingP2PForDownloading(_))
2295 .WillRepeatedly(SaveArg<0>(&actual_allow_p2p_for_downloading));
2296 EXPECT_CALL(mock_payload_state, SetUsingP2PForSharing(_))
2297 .WillRepeatedly(SaveArg<0>(&actual_allow_p2p_for_sharing));
2298 EXPECT_CALL(mock_payload_state, SetP2PUrl(_))
2299 .WillRepeatedly(SaveArg<0>(&actual_p2p_url));
2300
2301 MockP2PManager mock_p2p_manager;
2302 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
2303 mock_p2p_manager.fake().SetLookupUrlForFileResult(p2p_client_result_url);
2304
2305 TimeDelta timeout = TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds);
2306 EXPECT_CALL(mock_p2p_manager, LookupUrlForFile(_, _, timeout, _))
2307 .Times(expect_p2p_client_lookup ? 1 : 0);
2308
2309 fake_update_response_.disable_p2p_for_downloading =
2310 omaha_disable_p2p_for_downloading;
2311 fake_update_response_.disable_p2p_for_sharing = omaha_disable_p2p_for_sharing;
2312
2313 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2314 tuc_params_.expected_check_result = metrics::CheckResult::kUpdateAvailable;
2315
2316 ASSERT_TRUE(TestUpdateCheck());
2317 EXPECT_TRUE(response.update_exists);
2318
2319 EXPECT_EQ(omaha_disable_p2p_for_downloading,
2320 response.disable_p2p_for_downloading);
2321 EXPECT_EQ(omaha_disable_p2p_for_sharing, response.disable_p2p_for_sharing);
2322
2323 EXPECT_EQ(expected_allow_p2p_for_downloading,
2324 actual_allow_p2p_for_downloading);
2325 EXPECT_EQ(expected_allow_p2p_for_sharing, actual_allow_p2p_for_sharing);
2326 EXPECT_EQ(expected_p2p_url, actual_p2p_url);
2327 }
2328
TEST_F(OmahaRequestActionTest,P2PWithPeer)2329 TEST_F(OmahaRequestActionTest, P2PWithPeer) {
2330 P2PTest(true, // initial_allow_p2p_for_downloading
2331 true, // initial_allow_p2p_for_sharing
2332 false, // omaha_disable_p2p_for_downloading
2333 false, // omaha_disable_p2p_for_sharing
2334 true, // payload_state_allow_p2p_attempt
2335 true, // expect_p2p_client_lookup
2336 "http://1.3.5.7/p2p", // p2p_client_result_url
2337 true, // expected_allow_p2p_for_downloading
2338 true, // expected_allow_p2p_for_sharing
2339 "http://1.3.5.7/p2p"); // expected_p2p_url
2340 }
2341
TEST_F(OmahaRequestActionTest,P2PWithoutPeer)2342 TEST_F(OmahaRequestActionTest, P2PWithoutPeer) {
2343 P2PTest(true, // initial_allow_p2p_for_downloading
2344 true, // initial_allow_p2p_for_sharing
2345 false, // omaha_disable_p2p_for_downloading
2346 false, // omaha_disable_p2p_for_sharing
2347 true, // payload_state_allow_p2p_attempt
2348 true, // expect_p2p_client_lookup
2349 "", // p2p_client_result_url
2350 false, // expected_allow_p2p_for_downloading
2351 true, // expected_allow_p2p_for_sharing
2352 ""); // expected_p2p_url
2353 }
2354
TEST_F(OmahaRequestActionTest,P2PDownloadNotAllowed)2355 TEST_F(OmahaRequestActionTest, P2PDownloadNotAllowed) {
2356 P2PTest(false, // initial_allow_p2p_for_downloading
2357 true, // initial_allow_p2p_for_sharing
2358 false, // omaha_disable_p2p_for_downloading
2359 false, // omaha_disable_p2p_for_sharing
2360 true, // payload_state_allow_p2p_attempt
2361 false, // expect_p2p_client_lookup
2362 "unset", // p2p_client_result_url
2363 false, // expected_allow_p2p_for_downloading
2364 true, // expected_allow_p2p_for_sharing
2365 ""); // expected_p2p_url
2366 }
2367
TEST_F(OmahaRequestActionTest,P2PWithPeerDownloadDisabledByOmaha)2368 TEST_F(OmahaRequestActionTest, P2PWithPeerDownloadDisabledByOmaha) {
2369 P2PTest(true, // initial_allow_p2p_for_downloading
2370 true, // initial_allow_p2p_for_sharing
2371 true, // omaha_disable_p2p_for_downloading
2372 false, // omaha_disable_p2p_for_sharing
2373 true, // payload_state_allow_p2p_attempt
2374 false, // expect_p2p_client_lookup
2375 "unset", // p2p_client_result_url
2376 false, // expected_allow_p2p_for_downloading
2377 true, // expected_allow_p2p_for_sharing
2378 ""); // expected_p2p_url
2379 }
2380
TEST_F(OmahaRequestActionTest,P2PWithPeerSharingDisabledByOmaha)2381 TEST_F(OmahaRequestActionTest, P2PWithPeerSharingDisabledByOmaha) {
2382 P2PTest(true, // initial_allow_p2p_for_downloading
2383 true, // initial_allow_p2p_for_sharing
2384 false, // omaha_disable_p2p_for_downloading
2385 true, // omaha_disable_p2p_for_sharing
2386 true, // payload_state_allow_p2p_attempt
2387 true, // expect_p2p_client_lookup
2388 "http://1.3.5.7/p2p", // p2p_client_result_url
2389 true, // expected_allow_p2p_for_downloading
2390 false, // expected_allow_p2p_for_sharing
2391 "http://1.3.5.7/p2p"); // expected_p2p_url
2392 }
2393
TEST_F(OmahaRequestActionTest,P2PWithPeerBothDisabledByOmaha)2394 TEST_F(OmahaRequestActionTest, P2PWithPeerBothDisabledByOmaha) {
2395 P2PTest(true, // initial_allow_p2p_for_downloading
2396 true, // initial_allow_p2p_for_sharing
2397 true, // omaha_disable_p2p_for_downloading
2398 true, // omaha_disable_p2p_for_sharing
2399 true, // payload_state_allow_p2p_attempt
2400 false, // expect_p2p_client_lookup
2401 "unset", // p2p_client_result_url
2402 false, // expected_allow_p2p_for_downloading
2403 false, // expected_allow_p2p_for_sharing
2404 ""); // expected_p2p_url
2405 }
2406
InstallDateParseHelper(const string & elapsed_days,OmahaResponse * response)2407 bool OmahaRequestActionTest::InstallDateParseHelper(const string& elapsed_days,
2408 OmahaResponse* response) {
2409 fake_update_response_.elapsed_days = elapsed_days;
2410 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2411
2412 return TestUpdateCheck();
2413 }
2414
TEST_F(OmahaRequestActionTest,ParseInstallDateFromResponse)2415 TEST_F(OmahaRequestActionTest, ParseInstallDateFromResponse) {
2416 // Simulate a successful update check that happens during OOBE. The
2417 // deadline in the response is needed to force the update attempt to
2418 // occur; responses without a deadline seen during OOBE will normally
2419 // return ErrorCode::kNonCriticalUpdateInOOBE.
2420 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
2421 fake_update_response_.deadline = "20101020";
2422
2423 // Check that we parse elapsed_days in the Omaha Response correctly.
2424 // and that the kPrefsInstallDateDays value is written to.
2425 EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2426 EXPECT_TRUE(InstallDateParseHelper("42", &response));
2427 EXPECT_TRUE(response.update_exists);
2428 EXPECT_EQ(42, response.install_date_days);
2429 EXPECT_TRUE(fake_prefs_.Exists(kPrefsInstallDateDays));
2430 int64_t prefs_days;
2431 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2432 EXPECT_EQ(prefs_days, 42);
2433
2434 // If there already is a value set, we shouldn't do anything.
2435 EXPECT_TRUE(InstallDateParseHelper("7", &response));
2436 EXPECT_TRUE(response.update_exists);
2437 EXPECT_EQ(7, response.install_date_days);
2438 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2439 EXPECT_EQ(prefs_days, 42);
2440
2441 // Note that elapsed_days is not necessarily divisible by 7 so check
2442 // that we round down correctly when populating kPrefsInstallDateDays.
2443 EXPECT_TRUE(fake_prefs_.Delete(kPrefsInstallDateDays));
2444 EXPECT_TRUE(InstallDateParseHelper("23", &response));
2445 EXPECT_TRUE(response.update_exists);
2446 EXPECT_EQ(23, response.install_date_days);
2447 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2448 EXPECT_EQ(prefs_days, 21);
2449
2450 // Check that we correctly handle elapsed_days not being included in
2451 // the Omaha Response.
2452 EXPECT_TRUE(InstallDateParseHelper("", &response));
2453 EXPECT_TRUE(response.update_exists);
2454 EXPECT_EQ(-1, response.install_date_days);
2455 }
2456
2457 // If there is no prefs and OOBE is not complete, we should not
2458 // report anything to Omaha.
TEST_F(OmahaRequestActionTest,GetInstallDateWhenNoPrefsNorOOBE)2459 TEST_F(OmahaRequestActionTest, GetInstallDateWhenNoPrefsNorOOBE) {
2460 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
2461 EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
2462 EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2463 }
2464
2465 // If OOBE is complete and happened on a valid date (e.g. after Jan
2466 // 1 2007 0:00 PST), that date should be used and written to
2467 // prefs. However, first try with an invalid date and check we do
2468 // nothing.
TEST_F(OmahaRequestActionTest,GetInstallDateWhenOOBECompletedWithInvalidDate)2469 TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithInvalidDate) {
2470 Time oobe_date = Time::FromTimeT(42); // Dec 31, 1969 16:00:42 PST.
2471 fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2472 EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
2473 EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2474 }
2475
2476 // Then check with a valid date. The date Jan 20, 2007 0:00 PST
2477 // should yield an InstallDate of 14.
TEST_F(OmahaRequestActionTest,GetInstallDateWhenOOBECompletedWithValidDate)2478 TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithValidDate) {
2479 Time oobe_date = Time::FromTimeT(1169280000); // Jan 20, 2007 0:00 PST.
2480 fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2481 EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
2482 EXPECT_TRUE(fake_prefs_.Exists(kPrefsInstallDateDays));
2483
2484 int64_t prefs_days;
2485 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2486 EXPECT_EQ(prefs_days, 14);
2487 }
2488
2489 // Now that we have a valid date in prefs, check that we keep using
2490 // that even if OOBE date reports something else. The date Jan 30,
2491 // 2007 0:00 PST should yield an InstallDate of 28... but since
2492 // there's a prefs file, we should still get 14.
TEST_F(OmahaRequestActionTest,GetInstallDateWhenOOBECompletedDateChanges)2493 TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedDateChanges) {
2494 // Set a valid date in the prefs first.
2495 EXPECT_TRUE(fake_prefs_.SetInt64(kPrefsInstallDateDays, 14));
2496
2497 Time oobe_date = Time::FromTimeT(1170144000); // Jan 30, 2007 0:00 PST.
2498 fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2499 EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
2500
2501 int64_t prefs_days;
2502 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2503 EXPECT_EQ(prefs_days, 14);
2504
2505 // If we delete the prefs file, we should get 28 days.
2506 EXPECT_TRUE(fake_prefs_.Delete(kPrefsInstallDateDays));
2507 EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 28);
2508 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2509 EXPECT_EQ(prefs_days, 28);
2510 }
2511
2512 // Verifies that a device with no device policy, and is not a consumer
2513 // device sets the max kernel key version to the current version.
2514 // ie. the same behavior as if rollback is enabled.
TEST_F(OmahaRequestActionTest,NoPolicyEnterpriseDevicesSetMaxRollback)2515 TEST_F(OmahaRequestActionTest, NoPolicyEnterpriseDevicesSetMaxRollback) {
2516 FakeHardware* fake_hw = fake_system_state_.fake_hardware();
2517
2518 // Setup and verify some initial default values for the kernel TPM
2519 // values that control verified boot and rollback.
2520 const int min_kernel_version = 4;
2521 fake_hw->SetMinKernelKeyVersion(min_kernel_version);
2522 fake_hw->SetMaxKernelKeyRollforward(kRollforwardInfinity);
2523 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2524 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2525
2526 EXPECT_CALL(
2527 *fake_system_state_.mock_metrics_reporter(),
2528 ReportKeyVersionMetrics(min_kernel_version, min_kernel_version, true))
2529 .Times(1);
2530
2531 fake_update_response_.deadline = "20101020";
2532 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2533 tuc_params_.is_consumer_device = false;
2534 tuc_params_.rollback_allowed_milestones = 3;
2535
2536 EXPECT_TRUE(TestUpdateCheck());
2537 EXPECT_TRUE(response.update_exists);
2538
2539 // Verify kernel_max_rollforward was set to the current minimum
2540 // kernel key version. This has the effect of freezing roll
2541 // forwards indefinitely. This will hold the rollback window
2542 // open until a future change will be able to move this forward
2543 // relative the configured window.
2544 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2545 EXPECT_EQ(min_kernel_version, fake_hw->GetMaxKernelKeyRollforward());
2546 }
2547
2548 // Verifies that a conmsumer device with no device policy sets the
2549 // max kernel key version to the current version. ie. the same
2550 // behavior as if rollback is enabled.
TEST_F(OmahaRequestActionTest,NoPolicyConsumerDevicesSetMaxRollback)2551 TEST_F(OmahaRequestActionTest, NoPolicyConsumerDevicesSetMaxRollback) {
2552 FakeHardware* fake_hw = fake_system_state_.fake_hardware();
2553
2554 // Setup and verify some initial default values for the kernel TPM
2555 // values that control verified boot and rollback.
2556 const int min_kernel_version = 3;
2557 fake_hw->SetMinKernelKeyVersion(min_kernel_version);
2558 fake_hw->SetMaxKernelKeyRollforward(kRollforwardInfinity);
2559 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2560 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2561
2562 EXPECT_CALL(
2563 *fake_system_state_.mock_metrics_reporter(),
2564 ReportKeyVersionMetrics(min_kernel_version, kRollforwardInfinity, true))
2565 .Times(1);
2566
2567 fake_update_response_.deadline = "20101020";
2568 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2569 tuc_params_.is_consumer_device = true;
2570 tuc_params_.rollback_allowed_milestones = 3;
2571
2572 EXPECT_TRUE(TestUpdateCheck());
2573 EXPECT_TRUE(response.update_exists);
2574
2575 // Verify that with rollback disabled that kernel_max_rollforward
2576 // was set to logical infinity. This is the expected behavior for
2577 // consumer devices and matches the existing behavior prior to the
2578 // rollback features.
2579 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2580 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2581 }
2582
2583 // Verifies that a device with rollback enabled sets kernel_max_rollforward
2584 // in the TPM to prevent roll forward.
TEST_F(OmahaRequestActionTest,RollbackEnabledDevicesSetMaxRollback)2585 TEST_F(OmahaRequestActionTest, RollbackEnabledDevicesSetMaxRollback) {
2586 FakeHardware* fake_hw = fake_system_state_.fake_hardware();
2587
2588 // Setup and verify some initial default values for the kernel TPM
2589 // values that control verified boot and rollback.
2590 const int allowed_milestones = 4;
2591 const int min_kernel_version = 3;
2592 fake_hw->SetMinKernelKeyVersion(min_kernel_version);
2593 fake_hw->SetMaxKernelKeyRollforward(kRollforwardInfinity);
2594 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2595 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2596
2597 EXPECT_CALL(
2598 *fake_system_state_.mock_metrics_reporter(),
2599 ReportKeyVersionMetrics(min_kernel_version, min_kernel_version, true))
2600 .Times(1);
2601
2602 fake_update_response_.deadline = "20101020";
2603 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2604 tuc_params_.is_consumer_device = false;
2605 tuc_params_.rollback_allowed_milestones = allowed_milestones;
2606 tuc_params_.is_policy_loaded = true;
2607
2608 EXPECT_TRUE(TestUpdateCheck());
2609 EXPECT_TRUE(response.update_exists);
2610
2611 // Verify that with rollback enabled that kernel_max_rollforward
2612 // was set to the current minimum kernel key version. This has
2613 // the effect of freezing roll forwards indefinitely. This will
2614 // hold the rollback window open until a future change will
2615 // be able to move this forward relative the configured window.
2616 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2617 EXPECT_EQ(min_kernel_version, fake_hw->GetMaxKernelKeyRollforward());
2618 }
2619
2620 // Verifies that a device with rollback disabled sets kernel_max_rollforward
2621 // in the TPM to logical infinity, to allow roll forward.
TEST_F(OmahaRequestActionTest,RollbackDisabledDevicesSetMaxRollback)2622 TEST_F(OmahaRequestActionTest, RollbackDisabledDevicesSetMaxRollback) {
2623 FakeHardware* fake_hw = fake_system_state_.fake_hardware();
2624
2625 // Setup and verify some initial default values for the kernel TPM
2626 // values that control verified boot and rollback.
2627 const int allowed_milestones = 0;
2628 const int min_kernel_version = 3;
2629 fake_hw->SetMinKernelKeyVersion(min_kernel_version);
2630 fake_hw->SetMaxKernelKeyRollforward(kRollforwardInfinity);
2631 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2632 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2633
2634 EXPECT_CALL(
2635 *fake_system_state_.mock_metrics_reporter(),
2636 ReportKeyVersionMetrics(min_kernel_version, kRollforwardInfinity, true))
2637 .Times(1);
2638
2639 fake_update_response_.deadline = "20101020";
2640 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2641 tuc_params_.is_consumer_device = false;
2642 tuc_params_.rollback_allowed_milestones = allowed_milestones;
2643 tuc_params_.is_policy_loaded = true;
2644
2645 EXPECT_TRUE(TestUpdateCheck());
2646 EXPECT_TRUE(response.update_exists);
2647
2648 // Verify that with rollback disabled that kernel_max_rollforward
2649 // was set to logical infinity.
2650 EXPECT_EQ(min_kernel_version, fake_hw->GetMinKernelKeyVersion());
2651 EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
2652 }
2653
TEST_F(OmahaRequestActionTest,RollbackResponseParsedNoEntries)2654 TEST_F(OmahaRequestActionTest, RollbackResponseParsedNoEntries) {
2655 fake_update_response_.rollback = true;
2656 fake_update_response_.deadline = "20101020";
2657 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2658 tuc_params_.is_consumer_device = false;
2659 tuc_params_.rollback_allowed_milestones = 4;
2660 tuc_params_.is_policy_loaded = true;
2661
2662 EXPECT_TRUE(TestUpdateCheck());
2663 EXPECT_TRUE(response.update_exists);
2664 EXPECT_TRUE(response.is_rollback);
2665 }
2666
TEST_F(OmahaRequestActionTest,RollbackResponseValidVersionsParsed)2667 TEST_F(OmahaRequestActionTest, RollbackResponseValidVersionsParsed) {
2668 fake_update_response_.rollback_firmware_version = "1.2";
2669 fake_update_response_.rollback_kernel_version = "3.4";
2670 fake_update_response_.rollback = true;
2671 fake_update_response_.deadline = "20101020";
2672 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2673 tuc_params_.is_consumer_device = false;
2674 tuc_params_.rollback_allowed_milestones = 4;
2675 tuc_params_.is_policy_loaded = true;
2676
2677 EXPECT_TRUE(TestUpdateCheck());
2678 EXPECT_TRUE(response.update_exists);
2679 EXPECT_TRUE(response.is_rollback);
2680 EXPECT_EQ(1, response.rollback_key_version.firmware_key);
2681 EXPECT_EQ(2, response.rollback_key_version.firmware);
2682 EXPECT_EQ(3, response.rollback_key_version.kernel_key);
2683 EXPECT_EQ(4, response.rollback_key_version.kernel);
2684 }
2685
TEST_F(OmahaRequestActionTest,TestUpdateFirstSeenAtPrefPersistedIfUpdateExists)2686 TEST_F(OmahaRequestActionTest,
2687 TestUpdateFirstSeenAtPrefPersistedIfUpdateExists) {
2688 FakeClock fake_clock;
2689 Time now = Time::Now();
2690 fake_clock.SetWallclockTime(now);
2691 fake_system_state_.set_clock(&fake_clock);
2692 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2693
2694 ASSERT_TRUE(TestUpdateCheck());
2695
2696 EXPECT_TRUE(response.update_exists);
2697 EXPECT_TRUE(fake_prefs_.Exists(kPrefsUpdateFirstSeenAt));
2698
2699 int64_t stored_first_seen_at_time;
2700 EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateFirstSeenAt,
2701 &stored_first_seen_at_time));
2702 EXPECT_EQ(now.ToInternalValue(), stored_first_seen_at_time);
2703 }
2704
TEST_F(OmahaRequestActionTest,TestUpdateFirstSeenAtPrefNotPersistedIfUpdateFails)2705 TEST_F(OmahaRequestActionTest,
2706 TestUpdateFirstSeenAtPrefNotPersistedIfUpdateFails) {
2707 FakeClock fake_clock;
2708 Time now = Time::Now();
2709 fake_clock.SetWallclockTime(now);
2710 fake_system_state_.set_clock(&fake_clock);
2711
2712 tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
2713 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2714 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2715
2716 ASSERT_TRUE(TestUpdateCheck());
2717
2718 EXPECT_FALSE(response.update_exists);
2719 EXPECT_FALSE(fake_prefs_.Exists(kPrefsUpdateFirstSeenAt));
2720 }
2721
TEST_F(OmahaRequestActionTest,InstallTest)2722 TEST_F(OmahaRequestActionTest, InstallTest) {
2723 request_params_.set_is_install(true);
2724 request_params_.set_dlc_apps_params(
2725 {{request_params_.GetDlcAppId("dlc_no_0"), {.name = "dlc_no_0"}},
2726 {request_params_.GetDlcAppId("dlc_no_1"), {.name = "dlc_no_1"}}});
2727 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2728
2729 ASSERT_TRUE(TestUpdateCheck());
2730
2731 for (const auto& it : request_params_.dlc_apps_params()) {
2732 EXPECT_NE(string::npos, post_str.find("appid=\"" + it.first + "\""));
2733 }
2734 EXPECT_NE(string::npos,
2735 post_str.find("appid=\"" + fake_update_response_.app_id + "\""));
2736
2737 // Count number of updatecheck tag in response.
2738 int updatecheck_count = 0;
2739 size_t pos = 0;
2740 while ((pos = post_str.find("<updatecheck", pos)) != string::npos) {
2741 updatecheck_count++;
2742 pos++;
2743 }
2744 EXPECT_EQ(request_params_.dlc_apps_params().size(), updatecheck_count);
2745 EXPECT_TRUE(response.update_exists);
2746 }
2747
TEST_F(OmahaRequestActionTest,InstallMissingPlatformVersionTest)2748 TEST_F(OmahaRequestActionTest, InstallMissingPlatformVersionTest) {
2749 fake_update_response_.multi_app_skip_updatecheck = true;
2750 fake_update_response_.multi_app_no_update = false;
2751 request_params_.set_is_install(true);
2752 request_params_.set_dlc_apps_params(
2753 {{request_params_.GetDlcAppId("dlc_no_0"), {.name = "dlc_no_0"}},
2754 {request_params_.GetDlcAppId("dlc_no_1"), {.name = "dlc_no_1"}}});
2755 request_params_.set_app_id(fake_update_response_.app_id_skip_updatecheck);
2756 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2757
2758 ASSERT_TRUE(TestUpdateCheck());
2759
2760 EXPECT_TRUE(response.update_exists);
2761 EXPECT_EQ(fake_update_response_.current_version, response.version);
2762 }
2763
TEST_F(OmahaRequestActionTest,UpdateWithDlcTest)2764 TEST_F(OmahaRequestActionTest, UpdateWithDlcTest) {
2765 request_params_.set_dlc_apps_params(
2766 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}}});
2767 fake_update_response_.dlc_app_update = true;
2768 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2769 EXPECT_CALL(mock_excluder_, IsExcluded(_)).WillRepeatedly(Return(false));
2770 ASSERT_TRUE(TestUpdateCheck());
2771
2772 EXPECT_EQ(response.packages.size(), 2u);
2773 // Two candidate URLs.
2774 EXPECT_EQ(response.packages[1].payload_urls.size(), 2u);
2775 EXPECT_TRUE(response.update_exists);
2776 }
2777
TEST_F(OmahaRequestActionTest,UpdateWithPartiallyExcludedDlcTest)2778 TEST_F(OmahaRequestActionTest, UpdateWithPartiallyExcludedDlcTest) {
2779 request_params_.set_dlc_apps_params(
2780 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}}});
2781 fake_update_response_.dlc_app_update = true;
2782 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2783 // The first DLC candidate URL is excluded.
2784 EXPECT_CALL(mock_excluder_, IsExcluded(_))
2785 .WillOnce(Return(true))
2786 .WillOnce(Return(false));
2787 ASSERT_TRUE(TestUpdateCheck());
2788
2789 EXPECT_EQ(response.packages.size(), 2u);
2790 // One candidate URL.
2791 EXPECT_EQ(response.packages[1].payload_urls.size(), 1u);
2792 EXPECT_TRUE(response.update_exists);
2793 }
2794
TEST_F(OmahaRequestActionTest,UpdateWithExcludedDlcTest)2795 TEST_F(OmahaRequestActionTest, UpdateWithExcludedDlcTest) {
2796 request_params_.set_dlc_apps_params(
2797 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}}});
2798 fake_update_response_.dlc_app_update = true;
2799 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2800 // Both DLC candidate URLs are excluded.
2801 EXPECT_CALL(mock_excluder_, IsExcluded(_))
2802 .WillOnce(Return(true))
2803 .WillOnce(Return(true));
2804 ASSERT_TRUE(TestUpdateCheck());
2805
2806 EXPECT_EQ(response.packages.size(), 1u);
2807 EXPECT_TRUE(response.update_exists);
2808 }
2809
TEST_F(OmahaRequestActionTest,UpdateWithDeprecatedDlcTest)2810 TEST_F(OmahaRequestActionTest, UpdateWithDeprecatedDlcTest) {
2811 request_params_.set_dlc_apps_params(
2812 {{request_params_.GetDlcAppId(kDlcId2), {.name = kDlcId2}}});
2813 fake_update_response_.dlc_app_no_update = true;
2814 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2815 EXPECT_CALL(mock_excluder_, IsExcluded(_)).WillRepeatedly(Return(false));
2816 ASSERT_TRUE(TestUpdateCheck());
2817
2818 EXPECT_TRUE(response.update_exists);
2819 }
2820
TEST_F(OmahaRequestActionTest,UpdateWithDlcAndDeprecatedDlcTest)2821 TEST_F(OmahaRequestActionTest, UpdateWithDlcAndDeprecatedDlcTest) {
2822 request_params_.set_dlc_apps_params(
2823 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}},
2824 {request_params_.GetDlcAppId(kDlcId2), {.name = kDlcId2}}});
2825 fake_update_response_.dlc_app_update = true;
2826 fake_update_response_.dlc_app_no_update = true;
2827 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2828 EXPECT_CALL(mock_excluder_, IsExcluded(_)).WillRepeatedly(Return(false));
2829 ASSERT_TRUE(TestUpdateCheck());
2830
2831 EXPECT_TRUE(response.update_exists);
2832 }
2833
TEST_F(OmahaRequestActionTest,PastRollbackVersionsNoEntries)2834 TEST_F(OmahaRequestActionTest, PastRollbackVersionsNoEntries) {
2835 fake_update_response_.rollback = true;
2836 fake_update_response_.rollback_allowed_milestones = 4;
2837 request_params_.set_rollback_allowed_milestones(4);
2838 fake_update_response_.deadline = "20101020";
2839 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2840 tuc_params_.is_consumer_device = false;
2841 tuc_params_.rollback_allowed_milestones = 4;
2842 tuc_params_.is_policy_loaded = true;
2843
2844 EXPECT_TRUE(TestUpdateCheck());
2845 EXPECT_TRUE(response.update_exists);
2846 EXPECT_TRUE(response.is_rollback);
2847 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2848 response.past_rollback_key_version.firmware_key);
2849 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2850 response.past_rollback_key_version.firmware);
2851 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2852 response.past_rollback_key_version.kernel_key);
2853 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2854 response.past_rollback_key_version.kernel);
2855 }
2856
TEST_F(OmahaRequestActionTest,PastRollbackVersionsValidEntries)2857 TEST_F(OmahaRequestActionTest, PastRollbackVersionsValidEntries) {
2858 request_params_.set_rollback_allowed_milestones(4);
2859 fake_update_response_.rollback = true;
2860 fake_update_response_.rollback_allowed_milestones = 4;
2861 fake_update_response_.rollback_firmware_version = "4.3";
2862 fake_update_response_.rollback_kernel_version = "2.1";
2863 fake_update_response_.past_rollback_key_version =
2864 std::make_pair("16.15", "14.13");
2865 fake_update_response_.deadline = "20101020";
2866 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2867 tuc_params_.is_consumer_device = false;
2868 tuc_params_.rollback_allowed_milestones = 4;
2869 tuc_params_.is_policy_loaded = true;
2870
2871 EXPECT_TRUE(TestUpdateCheck());
2872 EXPECT_TRUE(response.update_exists);
2873 EXPECT_TRUE(response.is_rollback);
2874 EXPECT_EQ(16, response.past_rollback_key_version.firmware_key);
2875 EXPECT_EQ(15, response.past_rollback_key_version.firmware);
2876 EXPECT_EQ(14, response.past_rollback_key_version.kernel_key);
2877 EXPECT_EQ(13, response.past_rollback_key_version.kernel);
2878 }
2879
TEST_F(OmahaRequestActionTest,MismatchNumberOfVersions)2880 TEST_F(OmahaRequestActionTest, MismatchNumberOfVersions) {
2881 fake_update_response_.rollback = true;
2882 fake_update_response_.rollback_allowed_milestones = 2;
2883 fake_update_response_.deadline = "20101020";
2884 request_params_.set_rollback_allowed_milestones(4);
2885
2886 // Since |request_params_.rollback_allowed_milestones| is 4 but the response
2887 // is constructed with |fake_update_response_.rollback_allowed_milestones| set
2888 // to 2, OmahaRequestAction will look for the key values of N-4 version but
2889 // only the N-2 version will exist.
2890 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2891 tuc_params_.is_consumer_device = false;
2892 tuc_params_.rollback_allowed_milestones = 2;
2893 tuc_params_.is_policy_loaded = true;
2894
2895 EXPECT_TRUE(TestUpdateCheck());
2896 EXPECT_TRUE(response.update_exists);
2897 EXPECT_TRUE(response.is_rollback);
2898 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2899 response.past_rollback_key_version.firmware_key);
2900 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2901 response.past_rollback_key_version.firmware);
2902 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2903 response.past_rollback_key_version.kernel_key);
2904 EXPECT_EQ(std::numeric_limits<uint16_t>::max(),
2905 response.past_rollback_key_version.kernel);
2906 }
2907
TEST_F(OmahaRequestActionTest,IncludeRequisitionTest)2908 TEST_F(OmahaRequestActionTest, IncludeRequisitionTest) {
2909 request_params_.set_device_requisition("remora");
2910 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2911 ASSERT_TRUE(TestUpdateCheck());
2912 EXPECT_NE(string::npos, post_str.find("requisition=\"remora\""));
2913 }
2914
TEST_F(OmahaRequestActionTest,NoIncludeRequisitionTest)2915 TEST_F(OmahaRequestActionTest, NoIncludeRequisitionTest) {
2916 request_params_.set_device_requisition("");
2917 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
2918 ASSERT_TRUE(TestUpdateCheck());
2919 EXPECT_EQ(string::npos, post_str.find("requisition"));
2920 }
2921
TEST_F(OmahaRequestActionTest,PersistEolDateTest)2922 TEST_F(OmahaRequestActionTest, PersistEolDateTest) {
2923 tuc_params_.http_response =
2924 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2925 "protocol=\"3.0\"><app appid=\"foo\" status=\"ok\">"
2926 "<ping status=\"ok\"/><updatecheck status=\"noupdate\" "
2927 "_eol_date=\"200\" _foo=\"bar\"/></app></response>";
2928 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2929 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2930
2931 ASSERT_TRUE(TestUpdateCheck());
2932
2933 string eol_date;
2934 EXPECT_TRUE(
2935 fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
2936 EXPECT_EQ("200", eol_date);
2937 }
2938
TEST_F(OmahaRequestActionTest,PersistEolMissingDateTest)2939 TEST_F(OmahaRequestActionTest, PersistEolMissingDateTest) {
2940 tuc_params_.http_response =
2941 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2942 "protocol=\"3.0\"><app appid=\"foo\" status=\"ok\">"
2943 "<ping status=\"ok\"/><updatecheck status=\"noupdate\" "
2944 "_foo=\"bar\"/></app></response>";
2945 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2946 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2947
2948 const string kDate = "123";
2949 fake_system_state_.prefs()->SetString(kPrefsOmahaEolDate, kDate);
2950
2951 ASSERT_TRUE(TestUpdateCheck());
2952
2953 string eol_date;
2954 EXPECT_TRUE(
2955 fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
2956 EXPECT_EQ(kDate, eol_date);
2957 }
2958
TEST_F(OmahaRequestActionTest,PersistEolBadDateTest)2959 TEST_F(OmahaRequestActionTest, PersistEolBadDateTest) {
2960 tuc_params_.http_response =
2961 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
2962 "protocol=\"3.0\"><app appid=\"foo\" status=\"ok\">"
2963 "<ping status=\"ok\"/><updatecheck status=\"noupdate\" "
2964 "_eol_date=\"bad\" foo=\"bar\"/></app></response>";
2965 tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
2966 tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
2967
2968 ASSERT_TRUE(TestUpdateCheck());
2969
2970 string eol_date;
2971 EXPECT_TRUE(
2972 fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
2973 EXPECT_EQ(kEolDateInvalid, StringToEolDate(eol_date));
2974 }
2975
TEST_F(OmahaRequestActionDlcPingTest,StorePingReplyNoPing)2976 TEST_F(OmahaRequestActionDlcPingTest, StorePingReplyNoPing) {
2977 OmahaRequestParams::AppParams app_param = {.name = dlc_id_};
2978 request_params_.set_dlc_apps_params(
2979 {{request_params_.GetDlcAppId(dlc_id_), app_param}});
2980
2981 ASSERT_TRUE(TestUpdateCheck());
2982
2983 int64_t temp_int;
2984 // If there was no ping, the metadata files shouldn't exist yet.
2985 EXPECT_FALSE(fake_prefs_.GetInt64(active_key_, &temp_int));
2986 EXPECT_FALSE(fake_prefs_.GetInt64(last_active_key_, &temp_int));
2987 EXPECT_FALSE(fake_prefs_.GetInt64(last_rollcall_key_, &temp_int));
2988 }
2989
TEST_F(OmahaRequestActionDlcPingTest,StorePingReplyActiveTest)2990 TEST_F(OmahaRequestActionDlcPingTest, StorePingReplyActiveTest) {
2991 // Create Active value
2992 fake_prefs_.SetInt64(active_key_, 0);
2993
2994 OmahaRequestParams::AppParams app_param = {
2995 .active_counting_type = OmahaRequestParams::kDateBased,
2996 .name = dlc_id_,
2997 .ping_active = 1,
2998 .send_ping = true};
2999 request_params_.set_dlc_apps_params(
3000 {{request_params_.GetDlcAppId(dlc_id_), app_param}});
3001
3002 int64_t temp_int;
3003 string temp_str;
3004 ASSERT_TRUE(TestUpdateCheck());
3005 EXPECT_TRUE(fake_prefs_.GetInt64(active_key_, &temp_int));
3006 EXPECT_EQ(temp_int, kPingInactiveValue);
3007 EXPECT_TRUE(fake_prefs_.GetString(last_active_key_, &temp_str));
3008 EXPECT_EQ(temp_str, "4763");
3009 EXPECT_TRUE(fake_prefs_.GetString(last_rollcall_key_, &temp_str));
3010 EXPECT_EQ(temp_str, "4763");
3011 }
3012
TEST_F(OmahaRequestActionDlcPingTest,StorePingReplyInactiveTest)3013 TEST_F(OmahaRequestActionDlcPingTest, StorePingReplyInactiveTest) {
3014 // Create Active value
3015 fake_prefs_.SetInt64(active_key_, 0);
3016
3017 OmahaRequestParams::AppParams app_param = {
3018 .active_counting_type = OmahaRequestParams::kDateBased,
3019 .name = dlc_id_,
3020 .ping_active = 0,
3021 .send_ping = true};
3022 request_params_.set_dlc_apps_params(
3023 {{request_params_.GetDlcAppId(dlc_id_), app_param}});
3024
3025 // Set the previous active value to an older value than 4763.
3026 fake_prefs_.SetString(last_active_key_, "555");
3027
3028 int64_t temp_int;
3029 ASSERT_TRUE(TestUpdateCheck());
3030 EXPECT_TRUE(fake_prefs_.GetInt64(active_key_, &temp_int));
3031 EXPECT_EQ(temp_int, kPingInactiveValue);
3032 string temp_str;
3033 EXPECT_TRUE(fake_prefs_.GetString(last_active_key_, &temp_str));
3034 EXPECT_EQ(temp_str, "555");
3035 EXPECT_TRUE(fake_prefs_.GetString(last_rollcall_key_, &temp_str));
3036 EXPECT_EQ(temp_str, "4763");
3037 }
3038
TEST_F(OmahaRequestActionTest,OmahaResponseUpdateCanExcludeCheck)3039 TEST_F(OmahaRequestActionTest, OmahaResponseUpdateCanExcludeCheck) {
3040 request_params_.set_dlc_apps_params(
3041 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}}});
3042 fake_update_response_.dlc_app_update = true;
3043 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
3044
3045 EXPECT_CALL(mock_excluder_, IsExcluded(_)).WillRepeatedly(Return(false));
3046 ASSERT_TRUE(TestUpdateCheck());
3047 ASSERT_TRUE(delegate_.omaha_response_);
3048 const auto& packages = delegate_.omaha_response_->packages;
3049 ASSERT_EQ(packages.size(), 2);
3050
3051 EXPECT_FALSE(packages[0].can_exclude);
3052 EXPECT_TRUE(packages[1].can_exclude);
3053 }
3054
TEST_F(OmahaRequestActionTest,OmahaResponseInstallCannotExcludeCheck)3055 TEST_F(OmahaRequestActionTest, OmahaResponseInstallCannotExcludeCheck) {
3056 request_params_.set_is_install(true);
3057 request_params_.set_dlc_apps_params(
3058 {{request_params_.GetDlcAppId(kDlcId1), {.name = kDlcId1}}});
3059 fake_update_response_.dlc_app_update = true;
3060 tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
3061
3062 EXPECT_CALL(mock_excluder_, IsExcluded(_)).WillRepeatedly(Return(false));
3063 ASSERT_TRUE(TestUpdateCheck());
3064 ASSERT_TRUE(delegate_.omaha_response_);
3065 const auto& packages = delegate_.omaha_response_->packages;
3066 ASSERT_EQ(packages.size(), 2);
3067
3068 EXPECT_FALSE(packages[0].can_exclude);
3069 EXPECT_FALSE(packages[1].can_exclude);
3070 }
3071
3072 } // namespace chromeos_update_engine
3073