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