omaha_request_action_unittest.cc 135 KB

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